AudioTrack.java revision 18cb3b5a27148c7d4556db4a55e8c2bafafef32c
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, mChannelIndexMask, 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    // Convenience method for the constructor's parameter checks.
705    // This is where constructor IllegalArgumentException-s are thrown
706    // postconditions:
707    //    mChannelCount is valid
708    //    mChannels is valid
709    //    mAudioFormat is valid
710    //    mSampleRate is valid
711    //    mDataLoadMode is valid
712    private void audioParamCheck(int sampleRateInHz, int channelConfig, int channelIndexMask,
713                                 int audioFormat, int mode) {
714        //--------------
715        // sample rate, note these values are subject to change
716        if (sampleRateInHz < SAMPLE_RATE_HZ_MIN || sampleRateInHz > SAMPLE_RATE_HZ_MAX) {
717            throw new IllegalArgumentException(sampleRateInHz
718                    + "Hz is not a supported sample rate.");
719        }
720        mSampleRate = sampleRateInHz;
721
722        //--------------
723        // channel config
724        mChannelConfiguration = channelConfig;
725
726        switch (channelConfig) {
727        case AudioFormat.CHANNEL_OUT_DEFAULT: //AudioFormat.CHANNEL_CONFIGURATION_DEFAULT
728        case AudioFormat.CHANNEL_OUT_MONO:
729        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
730            mChannelCount = 1;
731            mChannels = AudioFormat.CHANNEL_OUT_MONO;
732            break;
733        case AudioFormat.CHANNEL_OUT_STEREO:
734        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
735            mChannelCount = 2;
736            mChannels = AudioFormat.CHANNEL_OUT_STEREO;
737            break;
738        default:
739            if (channelConfig == AudioFormat.CHANNEL_INVALID && channelIndexMask != 0) {
740                mChannelCount = 0;
741                break; // channel index configuration only
742            }
743            if (!isMultichannelConfigSupported(channelConfig)) {
744                // input channel configuration features unsupported channels
745                throw new IllegalArgumentException("Unsupported channel configuration.");
746            }
747            mChannels = channelConfig;
748            mChannelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig);
749        }
750        // check the channel index configuration (if present)
751        mChannelIndexMask = channelIndexMask;
752        if (mChannelIndexMask != 0) {
753            // restrictive: indexMask could allow up to AUDIO_CHANNEL_BITS_LOG2
754            final int indexMask = (1 << CHANNEL_COUNT_MAX) - 1;
755            if ((channelIndexMask & ~indexMask) != 0) {
756                throw new IllegalArgumentException("Unsupported channel index configuration "
757                        + channelIndexMask);
758            }
759            int channelIndexCount = Integer.bitCount(channelIndexMask);
760            if (mChannelCount == 0) {
761                 mChannelCount = channelIndexCount;
762            } else if (mChannelCount != channelIndexCount) {
763                throw new IllegalArgumentException("Channel count must match");
764            }
765        }
766
767        //--------------
768        // audio format
769        if (audioFormat == AudioFormat.ENCODING_DEFAULT) {
770            audioFormat = AudioFormat.ENCODING_PCM_16BIT;
771        }
772
773        if (!AudioFormat.isValidEncoding(audioFormat)) {
774            throw new IllegalArgumentException("Unsupported audio encoding.");
775        }
776        mAudioFormat = audioFormat;
777
778        //--------------
779        // audio load mode
780        if (((mode != MODE_STREAM) && (mode != MODE_STATIC)) ||
781                ((mode != MODE_STREAM) && !AudioFormat.isEncodingLinearPcm(mAudioFormat))) {
782            throw new IllegalArgumentException("Invalid mode.");
783        }
784        mDataLoadMode = mode;
785    }
786
787    /**
788     * Convenience method to check that the channel configuration (a.k.a channel mask) is supported
789     * @param channelConfig the mask to validate
790     * @return false if the AudioTrack can't be used with such a mask
791     */
792    private static boolean isMultichannelConfigSupported(int channelConfig) {
793        // check for unsupported channels
794        if ((channelConfig & SUPPORTED_OUT_CHANNELS) != channelConfig) {
795            loge("Channel configuration features unsupported channels");
796            return false;
797        }
798        final int channelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig);
799        if (channelCount > CHANNEL_COUNT_MAX) {
800            loge("Channel configuration contains too many channels " +
801                    channelCount + ">" + CHANNEL_COUNT_MAX);
802            return false;
803        }
804        // check for unsupported multichannel combinations:
805        // - FL/FR must be present
806        // - L/R channels must be paired (e.g. no single L channel)
807        final int frontPair =
808                AudioFormat.CHANNEL_OUT_FRONT_LEFT | AudioFormat.CHANNEL_OUT_FRONT_RIGHT;
809        if ((channelConfig & frontPair) != frontPair) {
810                loge("Front channels must be present in multichannel configurations");
811                return false;
812        }
813        final int backPair =
814                AudioFormat.CHANNEL_OUT_BACK_LEFT | AudioFormat.CHANNEL_OUT_BACK_RIGHT;
815        if ((channelConfig & backPair) != 0) {
816            if ((channelConfig & backPair) != backPair) {
817                loge("Rear channels can't be used independently");
818                return false;
819            }
820        }
821        final int sidePair =
822                AudioFormat.CHANNEL_OUT_SIDE_LEFT | AudioFormat.CHANNEL_OUT_SIDE_RIGHT;
823        if ((channelConfig & sidePair) != 0
824                && (channelConfig & sidePair) != sidePair) {
825            loge("Side channels can't be used independently");
826            return false;
827        }
828        return true;
829    }
830
831
832    // Convenience method for the constructor's audio buffer size check.
833    // preconditions:
834    //    mChannelCount is valid
835    //    mAudioFormat is valid
836    // postcondition:
837    //    mNativeBufferSizeInBytes is valid (multiple of frame size, positive)
838    private void audioBuffSizeCheck(int audioBufferSize) {
839        // NB: this section is only valid with PCM data.
840        //     To update when supporting compressed formats
841        int frameSizeInBytes;
842        if (AudioFormat.isEncodingLinearPcm(mAudioFormat)) {
843            frameSizeInBytes = mChannelCount
844                    * (AudioFormat.getBytesPerSample(mAudioFormat));
845        } else {
846            frameSizeInBytes = 1;
847        }
848        if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) {
849            throw new IllegalArgumentException("Invalid audio buffer size.");
850        }
851
852        mNativeBufferSizeInBytes = audioBufferSize;
853        mNativeBufferSizeInFrames = audioBufferSize / frameSizeInBytes;
854    }
855
856
857    /**
858     * Releases the native AudioTrack resources.
859     */
860    public void release() {
861        // even though native_release() stops the native AudioTrack, we need to stop
862        // AudioTrack subclasses too.
863        try {
864            stop();
865        } catch(IllegalStateException ise) {
866            // don't raise an exception, we're releasing the resources.
867        }
868        native_release();
869        mState = STATE_UNINITIALIZED;
870    }
871
872    @Override
873    protected void finalize() {
874        native_finalize();
875    }
876
877    //--------------------------------------------------------------------------
878    // Getters
879    //--------------------
880    /**
881     * Returns the minimum gain value, which is the constant 0.0.
882     * Gain values less than 0.0 will be clamped to 0.0.
883     * <p>The word "volume" in the API name is historical; this is actually a linear gain.
884     * @return the minimum value, which is the constant 0.0.
885     */
886    static public float getMinVolume() {
887        return GAIN_MIN;
888    }
889
890    /**
891     * Returns the maximum gain value, which is greater than or equal to 1.0.
892     * Gain values greater than the maximum will be clamped to the maximum.
893     * <p>The word "volume" in the API name is historical; this is actually a gain.
894     * expressed as a linear multiplier on sample values, where a maximum value of 1.0
895     * corresponds to a gain of 0 dB (sample values left unmodified).
896     * @return the maximum value, which is greater than or equal to 1.0.
897     */
898    static public float getMaxVolume() {
899        return GAIN_MAX;
900    }
901
902    /**
903     * Returns the configured audio data sample rate in Hz
904     */
905    public int getSampleRate() {
906        return mSampleRate;
907    }
908
909    /**
910     * Returns the current playback sample rate rate in Hz.
911     */
912    public int getPlaybackRate() {
913        return native_get_playback_rate();
914    }
915
916    /**
917     * Returns the current playback settings.
918     * See {@link #setPlaybackSettings(PlaybackSettings)} to set playback settings
919     * @return current {@link PlaybackSettings}.
920     * @throws IllegalStateException if track is not initialized.
921     */
922    public @NonNull PlaybackSettings getPlaybackSettings() {
923        float[] floatArray = new float[2];
924        int[] intArray = new int[2];
925        native_get_playback_settings(floatArray, intArray);
926        return new PlaybackSettings()
927                .setSpeed(floatArray[0])
928                .setPitch(floatArray[1])
929                .setAudioFallbackMode(intArray[0]);
930    }
931
932    /**
933     * Returns the configured audio data encoding. See {@link AudioFormat#ENCODING_PCM_8BIT},
934     * {@link AudioFormat#ENCODING_PCM_16BIT}, and {@link AudioFormat#ENCODING_PCM_FLOAT}.
935     */
936    public int getAudioFormat() {
937        return mAudioFormat;
938    }
939
940    /**
941     * Returns the type of audio stream this AudioTrack is configured for.
942     * Compare the result against {@link AudioManager#STREAM_VOICE_CALL},
943     * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING},
944     * {@link AudioManager#STREAM_MUSIC}, {@link AudioManager#STREAM_ALARM},
945     * {@link AudioManager#STREAM_NOTIFICATION}, or {@link AudioManager#STREAM_DTMF}.
946     */
947    public int getStreamType() {
948        return mStreamType;
949    }
950
951    /**
952     * Returns the configured channel position mask.
953     * <p> For example, refer to {@link AudioFormat#CHANNEL_OUT_MONO},
954     * {@link AudioFormat#CHANNEL_OUT_STEREO}, {@link AudioFormat#CHANNEL_OUT_5POINT1}.
955     * This method may return {@link AudioFormat#CHANNEL_INVALID} if
956     * a channel index mask is used. Consider
957     * {@link #getFormat()} instead, to obtain an {@link AudioFormat},
958     * which contains both the channel position mask and the channel index mask.
959     */
960    public int getChannelConfiguration() {
961        return mChannelConfiguration;
962    }
963
964    /**
965     * Returns the configured <code>AudioTrack</code> format.
966     * @return an {@link AudioFormat} containing the
967     * <code>AudioTrack</code> parameters at the time of configuration.
968     */
969    public @NonNull AudioFormat getFormat() {
970        AudioFormat.Builder builder = new AudioFormat.Builder()
971            .setSampleRate(mSampleRate)
972            .setEncoding(mAudioFormat);
973        if (mChannelConfiguration != AudioFormat.CHANNEL_INVALID) {
974            builder.setChannelMask(mChannelConfiguration);
975        }
976        if (mChannelIndexMask != AudioFormat.CHANNEL_INVALID /* 0 */) {
977            builder.setChannelIndexMask(mChannelIndexMask);
978        }
979        return builder.build();
980    }
981
982    /**
983     * Returns the configured number of channels.
984     */
985    public int getChannelCount() {
986        return mChannelCount;
987    }
988
989    /**
990     * Returns the state of the AudioTrack instance. This is useful after the
991     * AudioTrack instance has been created to check if it was initialized
992     * properly. This ensures that the appropriate resources have been acquired.
993     * @see #STATE_INITIALIZED
994     * @see #STATE_NO_STATIC_DATA
995     * @see #STATE_UNINITIALIZED
996     */
997    public int getState() {
998        return mState;
999    }
1000
1001    /**
1002     * Returns the playback state of the AudioTrack instance.
1003     * @see #PLAYSTATE_STOPPED
1004     * @see #PLAYSTATE_PAUSED
1005     * @see #PLAYSTATE_PLAYING
1006     */
1007    public int getPlayState() {
1008        synchronized (mPlayStateLock) {
1009            return mPlayState;
1010        }
1011    }
1012
1013    /**
1014     *  Returns the "native frame count" of the <code>AudioTrack</code> buffer.
1015     *  <p> If the track's creation mode is {@link #MODE_STATIC},
1016     *  it is equal to the specified bufferSizeInBytes on construction, converted to frame units.
1017     *  A static track's native frame count will not change.
1018     *  <p> If the track's creation mode is {@link #MODE_STREAM},
1019     *  it is greater than or equal to the specified bufferSizeInBytes converted to frame units.
1020     *  For streaming tracks, this value may be rounded up to a larger value if needed by
1021     *  the target output sink, and
1022     *  if the track is subsequently routed to a different output sink, the native
1023     *  frame count may enlarge to accommodate.
1024     *  See also {@link AudioManager#getProperty(String)} for key
1025     *  {@link AudioManager#PROPERTY_OUTPUT_FRAMES_PER_BUFFER}.
1026     *  @return current size in frames of the audio track buffer.
1027     *  @throws IllegalStateException
1028     */
1029    public int getNativeFrameCount() throws IllegalStateException {
1030        return native_get_native_frame_count();
1031    }
1032
1033    /**
1034     * Returns marker position expressed in frames.
1035     * @return marker position in wrapping frame units similar to {@link #getPlaybackHeadPosition},
1036     * or zero if marker is disabled.
1037     */
1038    public int getNotificationMarkerPosition() {
1039        return native_get_marker_pos();
1040    }
1041
1042    /**
1043     * Returns the notification update period expressed in frames.
1044     * Zero means that no position update notifications are being delivered.
1045     */
1046    public int getPositionNotificationPeriod() {
1047        return native_get_pos_update_period();
1048    }
1049
1050    /**
1051     * Returns the playback head position expressed in frames.
1052     * Though the "int" type is signed 32-bits, the value should be reinterpreted as if it is
1053     * unsigned 32-bits.  That is, the next position after 0x7FFFFFFF is (int) 0x80000000.
1054     * This is a continuously advancing counter.  It will wrap (overflow) periodically,
1055     * for example approximately once every 27:03:11 hours:minutes:seconds at 44.1 kHz.
1056     * It is reset to zero by {@link #flush()}, {@link #reloadStaticData()}, and {@link #stop()}.
1057     * If the track's creation mode is {@link #MODE_STATIC}, the return value indicates
1058     * the total number of frames played since reset,
1059     * <i>not</i> the current offset within the buffer.
1060     */
1061    public int getPlaybackHeadPosition() {
1062        return native_get_position();
1063    }
1064
1065    /**
1066     * Returns this track's estimated latency in milliseconds. This includes the latency due
1067     * to AudioTrack buffer size, AudioMixer (if any) and audio hardware driver.
1068     *
1069     * DO NOT UNHIDE. The existing approach for doing A/V sync has too many problems. We need
1070     * a better solution.
1071     * @hide
1072     */
1073    public int getLatency() {
1074        return native_get_latency();
1075    }
1076
1077    /**
1078     *  Returns the output sample rate in Hz for the specified stream type.
1079     */
1080    static public int getNativeOutputSampleRate(int streamType) {
1081        return native_get_output_sample_rate(streamType);
1082    }
1083
1084    /**
1085     * Returns the minimum buffer size required for the successful creation of an AudioTrack
1086     * object to be created in the {@link #MODE_STREAM} mode. Note that this size doesn't
1087     * guarantee a smooth playback under load, and higher values should be chosen according to
1088     * the expected frequency at which the buffer will be refilled with additional data to play.
1089     * For example, if you intend to dynamically set the source sample rate of an AudioTrack
1090     * to a higher value than the initial source sample rate, be sure to configure the buffer size
1091     * based on the highest planned sample rate.
1092     * @param sampleRateInHz the source sample rate expressed in Hz.
1093     * @param channelConfig describes the configuration of the audio channels.
1094     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
1095     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
1096     * @param audioFormat the format in which the audio data is represented.
1097     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
1098     *   {@link AudioFormat#ENCODING_PCM_8BIT},
1099     *   and {@link AudioFormat#ENCODING_PCM_FLOAT}.
1100     * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed,
1101     *   or {@link #ERROR} if unable to query for output properties,
1102     *   or the minimum buffer size expressed in bytes.
1103     */
1104    static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) {
1105        int channelCount = 0;
1106        switch(channelConfig) {
1107        case AudioFormat.CHANNEL_OUT_MONO:
1108        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
1109            channelCount = 1;
1110            break;
1111        case AudioFormat.CHANNEL_OUT_STEREO:
1112        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
1113            channelCount = 2;
1114            break;
1115        default:
1116            if (!isMultichannelConfigSupported(channelConfig)) {
1117                loge("getMinBufferSize(): Invalid channel configuration.");
1118                return ERROR_BAD_VALUE;
1119            } else {
1120                channelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig);
1121            }
1122        }
1123
1124        if (!AudioFormat.isValidEncoding(audioFormat)) {
1125            loge("getMinBufferSize(): Invalid audio format.");
1126            return ERROR_BAD_VALUE;
1127        }
1128
1129        // sample rate, note these values are subject to change
1130        if ( (sampleRateInHz < SAMPLE_RATE_HZ_MIN) || (sampleRateInHz > SAMPLE_RATE_HZ_MAX) ) {
1131            loge("getMinBufferSize(): " + sampleRateInHz + " Hz is not a supported sample rate.");
1132            return ERROR_BAD_VALUE;
1133        }
1134
1135        int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat);
1136        if (size <= 0) {
1137            loge("getMinBufferSize(): error querying hardware");
1138            return ERROR;
1139        }
1140        else {
1141            return size;
1142        }
1143    }
1144
1145    /**
1146     * Returns the audio session ID.
1147     *
1148     * @return the ID of the audio session this AudioTrack belongs to.
1149     */
1150    public int getAudioSessionId() {
1151        return mSessionId;
1152    }
1153
1154   /**
1155    * Poll for a timestamp on demand.
1156    * <p>
1157    * If you need to track timestamps during initial warmup or after a routing or mode change,
1158    * you should request a new timestamp once per second until the reported timestamps
1159    * show that the audio clock is stable.
1160    * Thereafter, query for a new timestamp approximately once every 10 seconds to once per minute.
1161    * Calling this method more often is inefficient.
1162    * It is also counter-productive to call this method more often than recommended,
1163    * because the short-term differences between successive timestamp reports are not meaningful.
1164    * If you need a high-resolution mapping between frame position and presentation time,
1165    * consider implementing that at application level, based on low-resolution timestamps.
1166    * <p>
1167    * The audio data at the returned position may either already have been
1168    * presented, or may have not yet been presented but is committed to be presented.
1169    * It is not possible to request the time corresponding to a particular position,
1170    * or to request the (fractional) position corresponding to a particular time.
1171    * If you need such features, consider implementing them at application level.
1172    *
1173    * @param timestamp a reference to a non-null AudioTimestamp instance allocated
1174    *        and owned by caller.
1175    * @return true if a timestamp is available, or false if no timestamp is available.
1176    *         If a timestamp if available,
1177    *         the AudioTimestamp instance is filled in with a position in frame units, together
1178    *         with the estimated time when that frame was presented or is committed to
1179    *         be presented.
1180    *         In the case that no timestamp is available, any supplied instance is left unaltered.
1181    *         A timestamp may be temporarily unavailable while the audio clock is stabilizing,
1182    *         or during and immediately after a route change.
1183    */
1184    // Add this text when the "on new timestamp" API is added:
1185    //   Use if you need to get the most recent timestamp outside of the event callback handler.
1186    public boolean getTimestamp(AudioTimestamp timestamp)
1187    {
1188        if (timestamp == null) {
1189            throw new IllegalArgumentException();
1190        }
1191        // It's unfortunate, but we have to either create garbage every time or use synchronized
1192        long[] longArray = new long[2];
1193        int ret = native_get_timestamp(longArray);
1194        if (ret != SUCCESS) {
1195            return false;
1196        }
1197        timestamp.framePosition = longArray[0];
1198        timestamp.nanoTime = longArray[1];
1199        return true;
1200    }
1201
1202
1203    //--------------------------------------------------------------------------
1204    // Initialization / configuration
1205    //--------------------
1206    /**
1207     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
1208     * for each periodic playback head position update.
1209     * Notifications will be received in the same thread as the one in which the AudioTrack
1210     * instance was created.
1211     * @param listener
1212     */
1213    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) {
1214        setPlaybackPositionUpdateListener(listener, null);
1215    }
1216
1217    /**
1218     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
1219     * for each periodic playback head position update.
1220     * Use this method to receive AudioTrack events in the Handler associated with another
1221     * thread than the one in which you created the AudioTrack instance.
1222     * @param listener
1223     * @param handler the Handler that will receive the event notification messages.
1224     */
1225    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener,
1226                                                    Handler handler) {
1227        if (listener != null) {
1228            mEventHandlerDelegate = new NativePositionEventHandlerDelegate(this, listener, handler);
1229        } else {
1230            mEventHandlerDelegate = null;
1231        }
1232    }
1233
1234
1235    private static float clampGainOrLevel(float gainOrLevel) {
1236        if (Float.isNaN(gainOrLevel)) {
1237            throw new IllegalArgumentException();
1238        }
1239        if (gainOrLevel < GAIN_MIN) {
1240            gainOrLevel = GAIN_MIN;
1241        } else if (gainOrLevel > GAIN_MAX) {
1242            gainOrLevel = GAIN_MAX;
1243        }
1244        return gainOrLevel;
1245    }
1246
1247
1248     /**
1249     * Sets the specified left and right output gain values on the AudioTrack.
1250     * <p>Gain values are clamped to the closed interval [0.0, max] where
1251     * max is the value of {@link #getMaxVolume}.
1252     * A value of 0.0 results in zero gain (silence), and
1253     * a value of 1.0 means unity gain (signal unchanged).
1254     * The default value is 1.0 meaning unity gain.
1255     * <p>The word "volume" in the API name is historical; this is actually a linear gain.
1256     * @param leftGain output gain for the left channel.
1257     * @param rightGain output gain for the right channel
1258     * @return error code or success, see {@link #SUCCESS},
1259     *    {@link #ERROR_INVALID_OPERATION}
1260     * @deprecated Applications should use {@link #setVolume} instead, as it
1261     * more gracefully scales down to mono, and up to multi-channel content beyond stereo.
1262     */
1263    public int setStereoVolume(float leftGain, float rightGain) {
1264        if (isRestricted()) {
1265            return SUCCESS;
1266        }
1267        if (mState == STATE_UNINITIALIZED) {
1268            return ERROR_INVALID_OPERATION;
1269        }
1270
1271        leftGain = clampGainOrLevel(leftGain);
1272        rightGain = clampGainOrLevel(rightGain);
1273
1274        native_setVolume(leftGain, rightGain);
1275
1276        return SUCCESS;
1277    }
1278
1279
1280    /**
1281     * Sets the specified output gain value on all channels of this track.
1282     * <p>Gain values are clamped to the closed interval [0.0, max] where
1283     * max is the value of {@link #getMaxVolume}.
1284     * A value of 0.0 results in zero gain (silence), and
1285     * a value of 1.0 means unity gain (signal unchanged).
1286     * The default value is 1.0 meaning unity gain.
1287     * <p>This API is preferred over {@link #setStereoVolume}, as it
1288     * more gracefully scales down to mono, and up to multi-channel content beyond stereo.
1289     * <p>The word "volume" in the API name is historical; this is actually a linear gain.
1290     * @param gain output gain for all channels.
1291     * @return error code or success, see {@link #SUCCESS},
1292     *    {@link #ERROR_INVALID_OPERATION}
1293     */
1294    public int setVolume(float gain) {
1295        return setStereoVolume(gain, gain);
1296    }
1297
1298
1299    /**
1300     * Sets the playback sample rate for this track. This sets the sampling rate at which
1301     * the audio data will be consumed and played back
1302     * (as set by the sampleRateInHz parameter in the
1303     * {@link #AudioTrack(int, int, int, int, int, int)} constructor),
1304     * not the original sampling rate of the
1305     * content. For example, setting it to half the sample rate of the content will cause the
1306     * playback to last twice as long, but will also result in a pitch shift down by one octave.
1307     * The valid sample rate range is from 1 Hz to twice the value returned by
1308     * {@link #getNativeOutputSampleRate(int)}.
1309     * Use {@link #setPlaybackSettings(PlaybackSettings)} for speed control.
1310     * @param sampleRateInHz the sample rate expressed in Hz
1311     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1312     *    {@link #ERROR_INVALID_OPERATION}
1313     */
1314    public int setPlaybackRate(int sampleRateInHz) {
1315        if (mState != STATE_INITIALIZED) {
1316            return ERROR_INVALID_OPERATION;
1317        }
1318        if (sampleRateInHz <= 0) {
1319            return ERROR_BAD_VALUE;
1320        }
1321        return native_set_playback_rate(sampleRateInHz);
1322    }
1323
1324
1325    /**
1326     * Sets the playback settings.
1327     * This method returns failure if it cannot apply the playback settings.
1328     * One possible cause is that the parameters for speed or pitch are out of range.
1329     * Another possible cause is that the <code>AudioTrack</code> is streaming
1330     * (see {@link #MODE_STREAM}) and the
1331     * buffer size is too small. For speeds greater than 1.0f, the <code>AudioTrack</code> buffer
1332     * on configuration must be larger than the speed multiplied by the minimum size
1333     * {@link #getMinBufferSize(int, int, int)}) to allow proper playback.
1334     * @param settings see {@link PlaybackSettings}. In particular,
1335     * speed, pitch, and audio mode should be set.
1336     * @throws IllegalArgumentException if the settings are invalid or not accepted.
1337     * @throws IllegalStateException if track is not initialized.
1338     */
1339    public void setPlaybackSettings(@NonNull PlaybackSettings settings) {
1340        if (settings == null) {
1341            throw new IllegalArgumentException("settings is null");
1342        }
1343        float[] floatArray;
1344        int[] intArray;
1345        try {
1346            floatArray = new float[] {
1347                    settings.getSpeed(),
1348                    settings.getPitch(),
1349            };
1350            intArray = new int[] {
1351                    settings.getAudioFallbackMode(),
1352                    PlaybackSettings.AUDIO_STRETCH_MODE_DEFAULT,
1353            };
1354        } catch (IllegalStateException e) {
1355            throw new IllegalArgumentException(e);
1356        }
1357        native_set_playback_settings(floatArray, intArray);
1358    }
1359
1360
1361    /**
1362     * Sets the position of the notification marker.  At most one marker can be active.
1363     * @param markerInFrames marker position in wrapping frame units similar to
1364     * {@link #getPlaybackHeadPosition}, or zero to disable the marker.
1365     * To set a marker at a position which would appear as zero due to wraparound,
1366     * a workaround is to use a non-zero position near zero, such as -1 or 1.
1367     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1368     *  {@link #ERROR_INVALID_OPERATION}
1369     */
1370    public int setNotificationMarkerPosition(int markerInFrames) {
1371        if (mState == STATE_UNINITIALIZED) {
1372            return ERROR_INVALID_OPERATION;
1373        }
1374        return native_set_marker_pos(markerInFrames);
1375    }
1376
1377
1378    /**
1379     * Sets the period for the periodic notification event.
1380     * @param periodInFrames update period expressed in frames.
1381     * Zero period means no position updates.  A negative period is not allowed.
1382     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION}
1383     */
1384    public int setPositionNotificationPeriod(int periodInFrames) {
1385        if (mState == STATE_UNINITIALIZED) {
1386            return ERROR_INVALID_OPERATION;
1387        }
1388        return native_set_pos_update_period(periodInFrames);
1389    }
1390
1391
1392    /**
1393     * Sets the playback head position within the static buffer.
1394     * The track must be stopped or paused for the position to be changed,
1395     * and must use the {@link #MODE_STATIC} mode.
1396     * @param positionInFrames playback head position within buffer, expressed in frames.
1397     * Zero corresponds to start of buffer.
1398     * The position must not be greater than the buffer size in frames, or negative.
1399     * Though this method and {@link #getPlaybackHeadPosition()} have similar names,
1400     * the position values have different meanings.
1401     * <br>
1402     * If looping is currently enabled and the new position is greater than or equal to the
1403     * loop end marker, the behavior varies by API level: for API level 22 and above,
1404     * the looping is first disabled and then the position is set.
1405     * For earlier API levels, the behavior is unspecified.
1406     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1407     *    {@link #ERROR_INVALID_OPERATION}
1408     */
1409    public int setPlaybackHeadPosition(int positionInFrames) {
1410        if (mDataLoadMode == MODE_STREAM || mState == STATE_UNINITIALIZED ||
1411                getPlayState() == PLAYSTATE_PLAYING) {
1412            return ERROR_INVALID_OPERATION;
1413        }
1414        if (!(0 <= positionInFrames && positionInFrames <= mNativeBufferSizeInFrames)) {
1415            return ERROR_BAD_VALUE;
1416        }
1417        return native_set_position(positionInFrames);
1418    }
1419
1420    /**
1421     * Sets the loop points and the loop count. The loop can be infinite.
1422     * Similarly to setPlaybackHeadPosition,
1423     * the track must be stopped or paused for the loop points to be changed,
1424     * and must use the {@link #MODE_STATIC} mode.
1425     * @param startInFrames loop start marker expressed in frames.
1426     * Zero corresponds to start of buffer.
1427     * The start marker must not be greater than or equal to the buffer size in frames, or negative.
1428     * @param endInFrames loop end marker expressed in frames.
1429     * The total buffer size in frames corresponds to end of buffer.
1430     * The end marker must not be greater than the buffer size in frames.
1431     * For looping, the end marker must not be less than or equal to the start marker,
1432     * but to disable looping
1433     * it is permitted for start marker, end marker, and loop count to all be 0.
1434     * If any input parameters are out of range, this method returns {@link #ERROR_BAD_VALUE}.
1435     * If the loop period (endInFrames - startInFrames) is too small for the implementation to
1436     * support,
1437     * {@link #ERROR_BAD_VALUE} is returned.
1438     * The loop range is the interval [startInFrames, endInFrames).
1439     * <br>
1440     * For API level 22 and above, the position is left unchanged,
1441     * unless it is greater than or equal to the loop end marker, in which case
1442     * it is forced to the loop start marker.
1443     * For earlier API levels, the effect on position is unspecified.
1444     * @param loopCount the number of times the loop is looped; must be greater than or equal to -1.
1445     *    A value of -1 means infinite looping, and 0 disables looping.
1446     *    A value of positive N means to "loop" (go back) N times.  For example,
1447     *    a value of one means to play the region two times in total.
1448     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1449     *    {@link #ERROR_INVALID_OPERATION}
1450     */
1451    public int setLoopPoints(int startInFrames, int endInFrames, int loopCount) {
1452        if (mDataLoadMode == MODE_STREAM || mState == STATE_UNINITIALIZED ||
1453                getPlayState() == PLAYSTATE_PLAYING) {
1454            return ERROR_INVALID_OPERATION;
1455        }
1456        if (loopCount == 0) {
1457            ;   // explicitly allowed as an exception to the loop region range check
1458        } else if (!(0 <= startInFrames && startInFrames < mNativeBufferSizeInFrames &&
1459                startInFrames < endInFrames && endInFrames <= mNativeBufferSizeInFrames)) {
1460            return ERROR_BAD_VALUE;
1461        }
1462        return native_set_loop(startInFrames, endInFrames, loopCount);
1463    }
1464
1465    /**
1466     * Sets the initialization state of the instance. This method was originally intended to be used
1467     * in an AudioTrack subclass constructor to set a subclass-specific post-initialization state.
1468     * However, subclasses of AudioTrack are no longer recommended, so this method is obsolete.
1469     * @param state the state of the AudioTrack instance
1470     * @deprecated Only accessible by subclasses, which are not recommended for AudioTrack.
1471     */
1472    @Deprecated
1473    protected void setState(int state) {
1474        mState = state;
1475    }
1476
1477
1478    //---------------------------------------------------------
1479    // Transport control methods
1480    //--------------------
1481    /**
1482     * Starts playing an AudioTrack.
1483     * If track's creation mode is {@link #MODE_STATIC}, you must have called one of
1484     * the {@link #write(byte[], int, int)}, {@link #write(short[], int, int)},
1485     * or {@link #write(float[], int, int, int)} methods.
1486     * If the mode is {@link #MODE_STREAM}, you can optionally prime the
1487     * output buffer by writing up to bufferSizeInBytes (from constructor) before starting.
1488     * This priming will avoid an immediate underrun, but is not required.
1489     *
1490     * @throws IllegalStateException
1491     */
1492    public void play()
1493    throws IllegalStateException {
1494        if (mState != STATE_INITIALIZED) {
1495            throw new IllegalStateException("play() called on uninitialized AudioTrack.");
1496        }
1497        if (isRestricted()) {
1498            setVolume(0);
1499        }
1500        synchronized(mPlayStateLock) {
1501            native_start();
1502            mPlayState = PLAYSTATE_PLAYING;
1503        }
1504    }
1505
1506    private boolean isRestricted() {
1507        if ((mAttributes.getFlags() & AudioAttributes.FLAG_BYPASS_INTERRUPTION_POLICY) != 0) {
1508            return false;
1509        }
1510        try {
1511            final int usage = AudioAttributes.usageForLegacyStreamType(mStreamType);
1512            final int mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO, usage,
1513                    Process.myUid(), ActivityThread.currentPackageName());
1514            return mode != AppOpsManager.MODE_ALLOWED;
1515        } catch (RemoteException e) {
1516            return false;
1517        }
1518    }
1519
1520    /**
1521     * Stops playing the audio data.
1522     * When used on an instance created in {@link #MODE_STREAM} mode, audio will stop playing
1523     * after the last buffer that was written has been played. For an immediate stop, use
1524     * {@link #pause()}, followed by {@link #flush()} to discard audio data that hasn't been played
1525     * back yet.
1526     * @throws IllegalStateException
1527     */
1528    public void stop()
1529    throws IllegalStateException {
1530        if (mState != STATE_INITIALIZED) {
1531            throw new IllegalStateException("stop() called on uninitialized AudioTrack.");
1532        }
1533
1534        // stop playing
1535        synchronized(mPlayStateLock) {
1536            native_stop();
1537            mPlayState = PLAYSTATE_STOPPED;
1538            mAvSyncHeader = null;
1539            mAvSyncBytesRemaining = 0;
1540        }
1541    }
1542
1543    /**
1544     * Pauses the playback of the audio data. Data that has not been played
1545     * back will not be discarded. Subsequent calls to {@link #play} will play
1546     * this data back. See {@link #flush()} to discard this data.
1547     *
1548     * @throws IllegalStateException
1549     */
1550    public void pause()
1551    throws IllegalStateException {
1552        if (mState != STATE_INITIALIZED) {
1553            throw new IllegalStateException("pause() called on uninitialized AudioTrack.");
1554        }
1555        //logd("pause()");
1556
1557        // pause playback
1558        synchronized(mPlayStateLock) {
1559            native_pause();
1560            mPlayState = PLAYSTATE_PAUSED;
1561        }
1562    }
1563
1564
1565    //---------------------------------------------------------
1566    // Audio data supply
1567    //--------------------
1568
1569    /**
1570     * Flushes the audio data currently queued for playback. Any data that has
1571     * been written but not yet presented will be discarded.  No-op if not stopped or paused,
1572     * or if the track's creation mode is not {@link #MODE_STREAM}.
1573     * <BR> Note that although data written but not yet presented is discarded, there is no
1574     * guarantee that all of the buffer space formerly used by that data
1575     * is available for a subsequent write.
1576     * For example, a call to {@link #write(byte[], int, int)} with <code>sizeInBytes</code>
1577     * less than or equal to the total buffer size
1578     * may return a short actual transfer count.
1579     */
1580    public void flush() {
1581        if (mState == STATE_INITIALIZED) {
1582            // flush the data in native layer
1583            native_flush();
1584            mAvSyncHeader = null;
1585            mAvSyncBytesRemaining = 0;
1586        }
1587
1588    }
1589
1590    /**
1591     * Writes the audio data to the audio sink for playback (streaming mode),
1592     * or copies audio data for later playback (static buffer mode).
1593     * The format specified in the AudioTrack constructor should be
1594     * {@link AudioFormat#ENCODING_PCM_8BIT} to correspond to the data in the array.
1595     * In streaming mode, will block until all data has been written to the audio sink.
1596     * In static buffer mode, copies the data to the buffer starting at offset 0.
1597     * Note that the actual playback of this data might occur after this function
1598     * returns. This function is thread safe with respect to {@link #stop} calls,
1599     * in which case all of the specified data might not be written to the audio sink.
1600     *
1601     * @param audioData the array that holds the data to play.
1602     * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
1603     *    starts.
1604     * @param sizeInBytes the number of bytes to read in audioData after the offset.
1605     * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION}
1606     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1607     *    the parameters don't resolve to valid data and indexes, or
1608     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1609     *    needs to be recreated.
1610     */
1611    public int write(@NonNull byte[] audioData, int offsetInBytes, int sizeInBytes) {
1612        return write(audioData, offsetInBytes, sizeInBytes, WRITE_BLOCKING);
1613    }
1614
1615    /**
1616     * Writes the audio data to the audio sink for playback (streaming mode),
1617     * or copies audio data for later playback (static buffer mode).
1618     * The format specified in the AudioTrack constructor should be
1619     * {@link AudioFormat#ENCODING_PCM_8BIT} to correspond to the data in the array.
1620     * In streaming mode, will block until all data has been written to the audio sink.
1621     * In static buffer mode, copies the data to the buffer starting at offset 0.
1622     * Note that the actual playback of this data might occur after this function
1623     * returns. This function is thread safe with respect to {@link #stop} calls,
1624     * in which case all of the specified data might not be written to the audio sink.
1625     *
1626     * @param audioData the array that holds the data to play.
1627     * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
1628     *    starts.
1629     * @param sizeInBytes the number of bytes to read in audioData after the offset.
1630     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1631     *     effect in static mode.
1632     *     <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1633     *         to the audio sink.
1634     *     <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1635     *     queuing as much audio data for playback as possible without blocking.
1636     * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION}
1637     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1638     *    the parameters don't resolve to valid data and indexes, or
1639     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1640     *    needs to be recreated.
1641     */
1642    public int write(@NonNull byte[] audioData, int offsetInBytes, int sizeInBytes,
1643            @WriteMode int writeMode) {
1644
1645        if (mState == STATE_UNINITIALIZED || mAudioFormat == AudioFormat.ENCODING_PCM_FLOAT) {
1646            return ERROR_INVALID_OPERATION;
1647        }
1648
1649        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1650            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1651            return ERROR_BAD_VALUE;
1652        }
1653
1654        if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0)
1655                || (offsetInBytes + sizeInBytes < 0)    // detect integer overflow
1656                || (offsetInBytes + sizeInBytes > audioData.length)) {
1657            return ERROR_BAD_VALUE;
1658        }
1659
1660        int ret = native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat,
1661                writeMode == WRITE_BLOCKING);
1662
1663        if ((mDataLoadMode == MODE_STATIC)
1664                && (mState == STATE_NO_STATIC_DATA)
1665                && (ret > 0)) {
1666            // benign race with respect to other APIs that read mState
1667            mState = STATE_INITIALIZED;
1668        }
1669
1670        return ret;
1671    }
1672
1673    /**
1674     * Writes the audio data to the audio sink for playback (streaming mode),
1675     * or copies audio data for later playback (static buffer mode).
1676     * The format specified in the AudioTrack constructor should be
1677     * {@link AudioFormat#ENCODING_PCM_16BIT} to correspond to the data in the array.
1678     * In streaming mode, will block until all data has been written to the audio sink.
1679     * In static buffer mode, copies the data to the buffer starting at offset 0.
1680     * Note that the actual playback of this data might occur after this function
1681     * returns. This function is thread safe with respect to {@link #stop} calls,
1682     * in which case all of the specified data might not be written to the audio sink.
1683     *
1684     * @param audioData the array that holds the data to play.
1685     * @param offsetInShorts the offset expressed in shorts in audioData where the data to play
1686     *     starts.
1687     * @param sizeInShorts the number of shorts to read in audioData after the offset.
1688     * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION}
1689     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1690     *    the parameters don't resolve to valid data and indexes, or
1691     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1692     *    needs to be recreated.
1693     */
1694    public int write(@NonNull short[] audioData, int offsetInShorts, int sizeInShorts) {
1695        return write(audioData, offsetInShorts, sizeInShorts, WRITE_BLOCKING);
1696    }
1697
1698    /**
1699     * Writes the audio data to the audio sink for playback (streaming mode),
1700     * or copies audio data for later playback (static buffer mode).
1701     * The format specified in the AudioTrack constructor should be
1702     * {@link AudioFormat#ENCODING_PCM_16BIT} to correspond to the data in the array.
1703     * In streaming mode, will block until all data has been written to the audio sink.
1704     * In static buffer mode, copies the data to the buffer starting at offset 0.
1705     * Note that the actual playback of this data might occur after this function
1706     * returns. This function is thread safe with respect to {@link #stop} calls,
1707     * in which case all of the specified data might not be written to the audio sink.
1708     *
1709     * @param audioData the array that holds the data to play.
1710     * @param offsetInShorts the offset expressed in shorts in audioData where the data to play
1711     *     starts.
1712     * @param sizeInShorts the number of shorts to read in audioData after the offset.
1713     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1714     *     effect in static mode.
1715     *     <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1716     *         to the audio sink.
1717     *     <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1718     *     queuing as much audio data for playback as possible without blocking.
1719     * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION}
1720     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1721     *    the parameters don't resolve to valid data and indexes, or
1722     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1723     *    needs to be recreated.
1724     */
1725    public int write(@NonNull short[] audioData, int offsetInShorts, int sizeInShorts,
1726            @WriteMode int writeMode) {
1727
1728        if (mState == STATE_UNINITIALIZED || mAudioFormat == AudioFormat.ENCODING_PCM_FLOAT) {
1729            return ERROR_INVALID_OPERATION;
1730        }
1731
1732        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1733            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1734            return ERROR_BAD_VALUE;
1735        }
1736
1737        if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0)
1738                || (offsetInShorts + sizeInShorts < 0)  // detect integer overflow
1739                || (offsetInShorts + sizeInShorts > audioData.length)) {
1740            return ERROR_BAD_VALUE;
1741        }
1742
1743        int ret = native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat,
1744                writeMode == WRITE_BLOCKING);
1745
1746        if ((mDataLoadMode == MODE_STATIC)
1747                && (mState == STATE_NO_STATIC_DATA)
1748                && (ret > 0)) {
1749            // benign race with respect to other APIs that read mState
1750            mState = STATE_INITIALIZED;
1751        }
1752
1753        return ret;
1754    }
1755
1756    /**
1757     * Writes the audio data to the audio sink for playback (streaming mode),
1758     * or copies audio data for later playback (static buffer mode).
1759     * The format specified in the AudioTrack constructor should be
1760     * {@link AudioFormat#ENCODING_PCM_FLOAT} to correspond to the data in the array.
1761     * In static buffer mode, copies the data to the buffer starting at offset 0,
1762     * and the write mode is ignored.
1763     * In streaming mode, the blocking behavior will depend on the write mode.
1764     * <p>
1765     * Note that the actual playback of this data might occur after this function
1766     * returns. This function is thread safe with respect to {@link #stop} calls,
1767     * in which case all of the specified data might not be written to the audio sink.
1768     * <p>
1769     * @param audioData the array that holds the data to play.
1770     *     The implementation does not clip for sample values within the nominal range
1771     *     [-1.0f, 1.0f], provided that all gains in the audio pipeline are
1772     *     less than or equal to unity (1.0f), and in the absence of post-processing effects
1773     *     that could add energy, such as reverb.  For the convenience of applications
1774     *     that compute samples using filters with non-unity gain,
1775     *     sample values +3 dB beyond the nominal range are permitted.
1776     *     However such values may eventually be limited or clipped, depending on various gains
1777     *     and later processing in the audio path.  Therefore applications are encouraged
1778     *     to provide samples values within the nominal range.
1779     * @param offsetInFloats the offset, expressed as a number of floats,
1780     *     in audioData where the data to play starts.
1781     * @param sizeInFloats the number of floats to read in audioData after the offset.
1782     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1783     *     effect in static mode.
1784     *     <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1785     *         to the audio sink.
1786     *     <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1787     *     queuing as much audio data for playback as possible without blocking.
1788     * @return the number of floats that were written, or {@link #ERROR_INVALID_OPERATION}
1789     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1790     *    the parameters don't resolve to valid data and indexes, or
1791     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1792     *    needs to be recreated.
1793     */
1794    public int write(@NonNull float[] audioData, int offsetInFloats, int sizeInFloats,
1795            @WriteMode int writeMode) {
1796
1797        if (mState == STATE_UNINITIALIZED) {
1798            Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED");
1799            return ERROR_INVALID_OPERATION;
1800        }
1801
1802        if (mAudioFormat != AudioFormat.ENCODING_PCM_FLOAT) {
1803            Log.e(TAG, "AudioTrack.write(float[] ...) requires format ENCODING_PCM_FLOAT");
1804            return ERROR_INVALID_OPERATION;
1805        }
1806
1807        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1808            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1809            return ERROR_BAD_VALUE;
1810        }
1811
1812        if ( (audioData == null) || (offsetInFloats < 0 ) || (sizeInFloats < 0)
1813                || (offsetInFloats + sizeInFloats < 0)  // detect integer overflow
1814                || (offsetInFloats + sizeInFloats > audioData.length)) {
1815            Log.e(TAG, "AudioTrack.write() called with invalid array, offset, or size");
1816            return ERROR_BAD_VALUE;
1817        }
1818
1819        int ret = native_write_float(audioData, offsetInFloats, sizeInFloats, mAudioFormat,
1820                writeMode == WRITE_BLOCKING);
1821
1822        if ((mDataLoadMode == MODE_STATIC)
1823                && (mState == STATE_NO_STATIC_DATA)
1824                && (ret > 0)) {
1825            // benign race with respect to other APIs that read mState
1826            mState = STATE_INITIALIZED;
1827        }
1828
1829        return ret;
1830    }
1831
1832
1833    /**
1834     * Writes the audio data to the audio sink for playback (streaming mode),
1835     * or copies audio data for later playback (static buffer mode).
1836     * In static buffer mode, copies the data to the buffer starting at its 0 offset, and the write
1837     * mode is ignored.
1838     * In streaming mode, the blocking behavior will depend on the write mode.
1839     * @param audioData the buffer that holds the data to play, starting at the position reported
1840     *     by <code>audioData.position()</code>.
1841     *     <BR>Note that upon return, the buffer position (<code>audioData.position()</code>) will
1842     *     have been advanced to reflect the amount of data that was successfully written to
1843     *     the AudioTrack.
1844     * @param sizeInBytes number of bytes to write.
1845     *     <BR>Note this may differ from <code>audioData.remaining()</code>, but cannot exceed it.
1846     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1847     *     effect in static mode.
1848     *     <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1849     *         to the audio sink.
1850     *     <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1851     *     queuing as much audio data for playback as possible without blocking.
1852     * @return 0 or a positive number of bytes that were written, or
1853     *     {@link #ERROR_BAD_VALUE}, {@link #ERROR_INVALID_OPERATION}, or
1854     *     {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1855     *     needs to be recreated.
1856     */
1857    public int write(@NonNull ByteBuffer audioData, int sizeInBytes,
1858            @WriteMode int writeMode) {
1859
1860        if (mState == STATE_UNINITIALIZED) {
1861            Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED");
1862            return ERROR_INVALID_OPERATION;
1863        }
1864
1865        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1866            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1867            return ERROR_BAD_VALUE;
1868        }
1869
1870        if ( (audioData == null) || (sizeInBytes < 0) || (sizeInBytes > audioData.remaining())) {
1871            Log.e(TAG, "AudioTrack.write() called with invalid size (" + sizeInBytes + ") value");
1872            return ERROR_BAD_VALUE;
1873        }
1874
1875        int ret = 0;
1876        if (audioData.isDirect()) {
1877            ret = native_write_native_bytes(audioData,
1878                    audioData.position(), sizeInBytes, mAudioFormat,
1879                    writeMode == WRITE_BLOCKING);
1880        } else {
1881            ret = native_write_byte(NioUtils.unsafeArray(audioData),
1882                    NioUtils.unsafeArrayOffset(audioData) + audioData.position(),
1883                    sizeInBytes, mAudioFormat,
1884                    writeMode == WRITE_BLOCKING);
1885        }
1886
1887        if ((mDataLoadMode == MODE_STATIC)
1888                && (mState == STATE_NO_STATIC_DATA)
1889                && (ret > 0)) {
1890            // benign race with respect to other APIs that read mState
1891            mState = STATE_INITIALIZED;
1892        }
1893
1894        if (ret > 0) {
1895            audioData.position(audioData.position() + ret);
1896        }
1897
1898        return ret;
1899    }
1900
1901    /**
1902     * Writes the audio data to the audio sink for playback (streaming mode) on a HW_AV_SYNC track.
1903     * In streaming mode, the blocking behavior will depend on the write mode.
1904     * @param audioData the buffer that holds the data to play, starting at the position reported
1905     *     by <code>audioData.position()</code>.
1906     *     <BR>Note that upon return, the buffer position (<code>audioData.position()</code>) will
1907     *     have been advanced to reflect the amount of data that was successfully written to
1908     *     the AudioTrack.
1909     * @param sizeInBytes number of bytes to write.
1910     *     <BR>Note this may differ from <code>audioData.remaining()</code>, but cannot exceed it.
1911     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}.
1912     *     <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1913     *         to the audio sink.
1914     *     <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1915     *     queuing as much audio data for playback as possible without blocking.
1916     * @param timestamp The timestamp of the first decodable audio frame in the provided audioData.
1917     * @return 0 or a positive number of bytes that were written, or
1918     *     {@link #ERROR_BAD_VALUE}, {@link #ERROR_INVALID_OPERATION}, or
1919     *     {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1920     *     needs to be recreated.
1921     */
1922    public int write(ByteBuffer audioData, int sizeInBytes,
1923            @WriteMode int writeMode, long timestamp) {
1924
1925        if ((mAttributes.getFlags() & AudioAttributes.FLAG_HW_AV_SYNC) == 0) {
1926            Log.d(TAG, "AudioTrack.write() called on a regular AudioTrack. Ignoring pts...");
1927            return write(audioData, sizeInBytes, writeMode);
1928        }
1929
1930        if ((audioData == null) || (sizeInBytes < 0) || (sizeInBytes > audioData.remaining())) {
1931            Log.e(TAG, "AudioTrack.write() called with invalid size (" + sizeInBytes + ") value");
1932            return ERROR_BAD_VALUE;
1933        }
1934
1935        // create timestamp header if none exists
1936        if (mAvSyncHeader == null) {
1937            mAvSyncHeader = ByteBuffer.allocate(16);
1938            mAvSyncHeader.order(ByteOrder.BIG_ENDIAN);
1939            mAvSyncHeader.putInt(0x55550001);
1940            mAvSyncHeader.putInt(sizeInBytes);
1941            mAvSyncHeader.putLong(timestamp);
1942            mAvSyncHeader.position(0);
1943            mAvSyncBytesRemaining = sizeInBytes;
1944        }
1945
1946        // write timestamp header if not completely written already
1947        int ret = 0;
1948        if (mAvSyncHeader.remaining() != 0) {
1949            ret = write(mAvSyncHeader, mAvSyncHeader.remaining(), writeMode);
1950            if (ret < 0) {
1951                Log.e(TAG, "AudioTrack.write() could not write timestamp header!");
1952                mAvSyncHeader = null;
1953                mAvSyncBytesRemaining = 0;
1954                return ret;
1955            }
1956            if (mAvSyncHeader.remaining() > 0) {
1957                Log.v(TAG, "AudioTrack.write() partial timestamp header written.");
1958                return 0;
1959            }
1960        }
1961
1962        // write audio data
1963        int sizeToWrite = Math.min(mAvSyncBytesRemaining, sizeInBytes);
1964        ret = write(audioData, sizeToWrite, writeMode);
1965        if (ret < 0) {
1966            Log.e(TAG, "AudioTrack.write() could not write audio data!");
1967            mAvSyncHeader = null;
1968            mAvSyncBytesRemaining = 0;
1969            return ret;
1970        }
1971
1972        mAvSyncBytesRemaining -= ret;
1973        if (mAvSyncBytesRemaining == 0) {
1974            mAvSyncHeader = null;
1975        }
1976
1977        return ret;
1978    }
1979
1980
1981    /**
1982     * Sets the playback head position within the static buffer to zero,
1983     * that is it rewinds to start of static buffer.
1984     * The track must be stopped or paused, and
1985     * the track's creation mode must be {@link #MODE_STATIC}.
1986     * <p>
1987     * For API level 22 and above, also resets the value returned by
1988     * {@link #getPlaybackHeadPosition()} to zero.
1989     * For earlier API levels, the reset behavior is unspecified.
1990     * <p>
1991     * {@link #setPlaybackHeadPosition(int)} to zero
1992     * is recommended instead when the reset of {@link #getPlaybackHeadPosition} is not needed.
1993     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1994     *  {@link #ERROR_INVALID_OPERATION}
1995     */
1996    public int reloadStaticData() {
1997        if (mDataLoadMode == MODE_STREAM || mState != STATE_INITIALIZED) {
1998            return ERROR_INVALID_OPERATION;
1999        }
2000        return native_reload_static();
2001    }
2002
2003    //--------------------------------------------------------------------------
2004    // Audio effects management
2005    //--------------------
2006
2007    /**
2008     * Attaches an auxiliary effect to the audio track. A typical auxiliary
2009     * effect is a reverberation effect which can be applied on any sound source
2010     * that directs a certain amount of its energy to this effect. This amount
2011     * is defined by setAuxEffectSendLevel().
2012     * {@see #setAuxEffectSendLevel(float)}.
2013     * <p>After creating an auxiliary effect (e.g.
2014     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
2015     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling
2016     * this method to attach the audio track to the effect.
2017     * <p>To detach the effect from the audio track, call this method with a
2018     * null effect id.
2019     *
2020     * @param effectId system wide unique id of the effect to attach
2021     * @return error code or success, see {@link #SUCCESS},
2022     *    {@link #ERROR_INVALID_OPERATION}, {@link #ERROR_BAD_VALUE}
2023     */
2024    public int attachAuxEffect(int effectId) {
2025        if (mState == STATE_UNINITIALIZED) {
2026            return ERROR_INVALID_OPERATION;
2027        }
2028        return native_attachAuxEffect(effectId);
2029    }
2030
2031    /**
2032     * Sets the send level of the audio track to the attached auxiliary effect
2033     * {@link #attachAuxEffect(int)}.  Effect levels
2034     * are clamped to the closed interval [0.0, max] where
2035     * max is the value of {@link #getMaxVolume}.
2036     * A value of 0.0 results in no effect, and a value of 1.0 is full send.
2037     * <p>By default the send level is 0.0f, so even if an effect is attached to the player
2038     * this method must be called for the effect to be applied.
2039     * <p>Note that the passed level value is a linear scalar. UI controls should be scaled
2040     * logarithmically: the gain applied by audio framework ranges from -72dB to at least 0dB,
2041     * so an appropriate conversion from linear UI input x to level is:
2042     * x == 0 -&gt; level = 0
2043     * 0 &lt; x &lt;= R -&gt; level = 10^(72*(x-R)/20/R)
2044     *
2045     * @param level linear send level
2046     * @return error code or success, see {@link #SUCCESS},
2047     *    {@link #ERROR_INVALID_OPERATION}, {@link #ERROR}
2048     */
2049    public int setAuxEffectSendLevel(float level) {
2050        if (isRestricted()) {
2051            return SUCCESS;
2052        }
2053        if (mState == STATE_UNINITIALIZED) {
2054            return ERROR_INVALID_OPERATION;
2055        }
2056        level = clampGainOrLevel(level);
2057        int err = native_setAuxEffectSendLevel(level);
2058        return err == 0 ? SUCCESS : ERROR;
2059    }
2060
2061    //--------------------------------------------------------------------------
2062    // Explicit Routing
2063    //--------------------
2064    private AudioDeviceInfo mPreferredDevice = null;
2065
2066    /**
2067     * Specifies an audio device (via an {@link AudioDeviceInfo} object) to route
2068     * the output from this AudioTrack.
2069     * @param deviceInfo The {@link AudioDeviceInfo} specifying the audio sink.
2070     *  If deviceInfo is null, default routing is restored.
2071     * @return true if succesful, false if the specified {@link AudioDeviceInfo} is non-null and
2072     * does not correspond to a valid audio output device.
2073     */
2074    public boolean setPreferredOutputDevice(AudioDeviceInfo deviceInfo) {
2075        // Do some validation....
2076        if (deviceInfo != null && !deviceInfo.isSink()) {
2077            return false;
2078        }
2079
2080        mPreferredDevice = deviceInfo;
2081        int preferredDeviceId = mPreferredDevice != null ? deviceInfo.getId() : 0;
2082
2083        return native_setOutputDevice(preferredDeviceId);
2084    }
2085
2086    /**
2087     * Returns the selected output specified by {@link #setPreferredOutputDevice}. Note that this
2088     * is not guaranteed to correspond to the actual device being used for playback.
2089     */
2090    public AudioDeviceInfo getPreferredOutputDevice() {
2091        return mPreferredDevice;
2092    }
2093
2094    //--------------------------------------------------------------------------
2095    // (Re)Routing Info
2096    //--------------------
2097    /**
2098     * Returns an {@link AudioDeviceInfo} identifying the current routing of this AudioTrack.
2099     */
2100    public AudioDeviceInfo getRoutedDevice() {
2101        return null;
2102    }
2103
2104    /**
2105     * The message sent to apps when the routing of this AudioTrack changes if they provide
2106     * a {#link Handler} object to addOnAudioTrackRoutingListener().
2107     */
2108    private ArrayMap<OnAudioTrackRoutingListener, NativeRoutingEventHandlerDelegate>
2109        mRoutingChangeListeners =
2110            new ArrayMap<OnAudioTrackRoutingListener, NativeRoutingEventHandlerDelegate>();
2111
2112    /**
2113     * Adds an {@link OnAudioTrackRoutingListener} to receive notifications of routing changes
2114     * on this AudioTrack.
2115     */
2116    public void addOnAudioTrackRoutingListener(OnAudioTrackRoutingListener listener,
2117            android.os.Handler handler) {
2118        if (listener != null && !mRoutingChangeListeners.containsKey(listener)) {
2119            synchronized (mRoutingChangeListeners) {
2120                mRoutingChangeListeners.put(
2121                    listener, new NativeRoutingEventHandlerDelegate(this, listener, handler));
2122            }
2123        }
2124    }
2125
2126    /**
2127     * Removes an {@link OnAudioTrackRoutingListener} which has been previously added
2128     * to receive notifications of changes to the set of connected audio devices.
2129     */
2130    public void removeOnAudioTrackRoutingListener(OnAudioTrackRoutingListener listener) {
2131        synchronized (mRoutingChangeListeners) {
2132            if (mRoutingChangeListeners.containsKey(listener)) {
2133                mRoutingChangeListeners.remove(listener);
2134            }
2135        }
2136    }
2137
2138    /**
2139     * Sends device list change notification to all listeners.
2140     */
2141    private void broadcastRoutingChange() {
2142        Collection<NativeRoutingEventHandlerDelegate> values;
2143        synchronized (mRoutingChangeListeners) {
2144            values = mRoutingChangeListeners.values();
2145        }
2146        for(NativeRoutingEventHandlerDelegate delegate : values) {
2147            Handler handler = delegate.getHandler();
2148            if (handler != null) {
2149                handler.sendEmptyMessage(NATIVE_EVENT_ROUTING_CHANGE);
2150            }
2151        }
2152    }
2153
2154    //---------------------------------------------------------
2155    // Interface definitions
2156    //--------------------
2157    /**
2158     * Interface definition for a callback to be invoked when the playback head position of
2159     * an AudioTrack has reached a notification marker or has increased by a certain period.
2160     */
2161    public interface OnPlaybackPositionUpdateListener  {
2162        /**
2163         * Called on the listener to notify it that the previously set marker has been reached
2164         * by the playback head.
2165         */
2166        void onMarkerReached(AudioTrack track);
2167
2168        /**
2169         * Called on the listener to periodically notify it that the playback head has reached
2170         * a multiple of the notification period.
2171         */
2172        void onPeriodicNotification(AudioTrack track);
2173    }
2174
2175    //---------------------------------------------------------
2176    // Inner classes
2177    //--------------------
2178    /**
2179     * Helper class to handle the forwarding of native events to the appropriate listener
2180     * (potentially) handled in a different thread
2181     */
2182    private class NativePositionEventHandlerDelegate {
2183        private final Handler mHandler;
2184
2185        NativePositionEventHandlerDelegate(final AudioTrack track,
2186                                   final OnPlaybackPositionUpdateListener listener,
2187                                   Handler handler) {
2188            // find the looper for our new event handler
2189            Looper looper;
2190            if (handler != null) {
2191                looper = handler.getLooper();
2192            } else {
2193                // no given handler, use the looper the AudioTrack was created in
2194                looper = mInitializationLooper;
2195            }
2196
2197            // construct the event handler with this looper
2198            if (looper != null) {
2199                // implement the event handler delegate
2200                mHandler = new Handler(looper) {
2201                    @Override
2202                    public void handleMessage(Message msg) {
2203                        if (track == null) {
2204                            return;
2205                        }
2206                        switch(msg.what) {
2207                        case NATIVE_EVENT_MARKER:
2208                            if (listener != null) {
2209                                listener.onMarkerReached(track);
2210                            }
2211                            break;
2212                        case NATIVE_EVENT_NEW_POS:
2213                            if (listener != null) {
2214                                listener.onPeriodicNotification(track);
2215                            }
2216                            break;
2217                        default:
2218                            loge("Unknown native event type: " + msg.what);
2219                            break;
2220                        }
2221                    }
2222                };
2223            } else {
2224                mHandler = null;
2225            }
2226        }
2227
2228        Handler getHandler() {
2229            return mHandler;
2230        }
2231    }
2232
2233    /**
2234     * Helper class to handle the forwarding of native events to the appropriate listener
2235     * (potentially) handled in a different thread
2236     */
2237    private class NativeRoutingEventHandlerDelegate {
2238        private final Handler mHandler;
2239
2240        NativeRoutingEventHandlerDelegate(final AudioTrack track,
2241                                   final OnAudioTrackRoutingListener listener,
2242                                   Handler handler) {
2243            // find the looper for our new event handler
2244            Looper looper;
2245            if (handler != null) {
2246                looper = handler.getLooper();
2247            } else {
2248                // no given handler, use the looper the AudioTrack was created in
2249                looper = mInitializationLooper;
2250            }
2251
2252            // construct the event handler with this looper
2253            if (looper != null) {
2254                // implement the event handler delegate
2255                mHandler = new Handler(looper) {
2256                    @Override
2257                    public void handleMessage(Message msg) {
2258                        if (track == null) {
2259                            return;
2260                        }
2261                        switch(msg.what) {
2262                        case NATIVE_EVENT_ROUTING_CHANGE:
2263                            if (listener != null) {
2264                                listener.onAudioTrackRouting(track);
2265                            }
2266                            break;
2267                        default:
2268                            loge("Unknown native event type: " + msg.what);
2269                            break;
2270                        }
2271                    }
2272                };
2273            } else {
2274                mHandler = null;
2275            }
2276        }
2277
2278        Handler getHandler() {
2279            return mHandler;
2280        }
2281    }
2282
2283    //---------------------------------------------------------
2284    // Java methods called from the native side
2285    //--------------------
2286    @SuppressWarnings("unused")
2287    private static void postEventFromNative(Object audiotrack_ref,
2288            int what, int arg1, int arg2, Object obj) {
2289        //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2);
2290        AudioTrack track = (AudioTrack)((WeakReference)audiotrack_ref).get();
2291        if (track == null) {
2292            return;
2293        }
2294
2295        NativePositionEventHandlerDelegate delegate = track.mEventHandlerDelegate;
2296        if (delegate != null) {
2297            Handler handler = delegate.getHandler();
2298            if (handler != null) {
2299                Message m = handler.obtainMessage(what, arg1, arg2, obj);
2300                handler.sendMessage(m);
2301            }
2302        }
2303
2304    }
2305
2306
2307    //---------------------------------------------------------
2308    // Native methods called from the Java side
2309    //--------------------
2310
2311    // post-condition: mStreamType is overwritten with a value
2312    //     that reflects the audio attributes (e.g. an AudioAttributes object with a usage of
2313    //     AudioAttributes.USAGE_MEDIA will map to AudioManager.STREAM_MUSIC
2314    private native final int native_setup(Object /*WeakReference<AudioTrack>*/ audiotrack_this,
2315            Object /*AudioAttributes*/ attributes,
2316            int sampleRate, int channelMask, int channelIndexMask, int audioFormat,
2317            int buffSizeInBytes, int mode, int[] sessionId);
2318
2319    private native final void native_finalize();
2320
2321    private native final void native_release();
2322
2323    private native final void native_start();
2324
2325    private native final void native_stop();
2326
2327    private native final void native_pause();
2328
2329    private native final void native_flush();
2330
2331    private native final int native_write_byte(byte[] audioData,
2332                                               int offsetInBytes, int sizeInBytes, int format,
2333                                               boolean isBlocking);
2334
2335    private native final int native_write_short(short[] audioData,
2336                                                int offsetInShorts, int sizeInShorts, int format,
2337                                                boolean isBlocking);
2338
2339    private native final int native_write_float(float[] audioData,
2340                                                int offsetInFloats, int sizeInFloats, int format,
2341                                                boolean isBlocking);
2342
2343    private native final int native_write_native_bytes(Object audioData,
2344            int positionInBytes, int sizeInBytes, int format, boolean blocking);
2345
2346    private native final int native_reload_static();
2347
2348    private native final int native_get_native_frame_count();
2349
2350    private native final void native_setVolume(float leftVolume, float rightVolume);
2351
2352    private native final int native_set_playback_rate(int sampleRateInHz);
2353    private native final int native_get_playback_rate();
2354
2355    // floatArray must be a non-null array of length >= 2
2356    // [0] is speed
2357    // [1] is pitch
2358    // intArray must be a non-null array of length >= 2
2359    // [0] is audio fallback mode
2360    // [1] is audio stretch mode
2361    private native final void native_set_playback_settings(float[] floatArray, int[] intArray);
2362    private native final void native_get_playback_settings(float[] floatArray, int[] intArray);
2363
2364    private native final int native_set_marker_pos(int marker);
2365    private native final int native_get_marker_pos();
2366
2367    private native final int native_set_pos_update_period(int updatePeriod);
2368    private native final int native_get_pos_update_period();
2369
2370    private native final int native_set_position(int position);
2371    private native final int native_get_position();
2372
2373    private native final int native_get_latency();
2374
2375    // longArray must be a non-null array of length >= 2
2376    // [0] is assigned the frame position
2377    // [1] is assigned the time in CLOCK_MONOTONIC nanoseconds
2378    private native final int native_get_timestamp(long[] longArray);
2379
2380    private native final int native_set_loop(int start, int end, int loopCount);
2381
2382    static private native final int native_get_output_sample_rate(int streamType);
2383    static private native final int native_get_min_buff_size(
2384            int sampleRateInHz, int channelConfig, int audioFormat);
2385
2386    private native final int native_attachAuxEffect(int effectId);
2387    private native final int native_setAuxEffectSendLevel(float level);
2388
2389    private native final boolean native_setOutputDevice(int deviceId);
2390
2391    //---------------------------------------------------------
2392    // Utility methods
2393    //------------------
2394
2395    private static void logd(String msg) {
2396        Log.d(TAG, msg);
2397    }
2398
2399    private static void loge(String msg) {
2400        Log.e(TAG, msg);
2401    }
2402}
2403