android_media_AudioTrack.cpp revision 973b8851eecbdcbab4992be01aaab568fd371a0a
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//#define LOG_NDEBUG 0
17
18#define LOG_TAG "AudioTrack-JNI"
19
20#include "android_media_AudioTrack.h"
21
22#include <JNIHelp.h>
23#include <JniConstants.h>
24#include "core_jni_helpers.h"
25
26#include "ScopedBytes.h"
27
28#include <utils/Log.h>
29#include <media/AudioSystem.h>
30#include <media/AudioTrack.h>
31#include <audio_utils/primitives.h>
32
33#include <binder/MemoryHeapBase.h>
34#include <binder/MemoryBase.h>
35
36#include "android_media_AudioFormat.h"
37#include "android_media_AudioErrors.h"
38#include "android_media_PlaybackParams.h"
39#include "android_media_DeviceCallback.h"
40
41// ----------------------------------------------------------------------------
42
43using namespace android;
44
45// ----------------------------------------------------------------------------
46static const char* const kClassPathName = "android/media/AudioTrack";
47static const char* const kAudioAttributesClassPathName = "android/media/AudioAttributes";
48
49struct audio_track_fields_t {
50    // these fields provide access from C++ to the...
51    jmethodID postNativeEventInJava; //... event post callback method
52    jfieldID  nativeTrackInJavaObj;  // stores in Java the native AudioTrack object
53    jfieldID  jniData;      // stores in Java additional resources used by the native AudioTrack
54    jfieldID  fieldStreamType; // ... mStreamType field in the AudioTrack Java object
55};
56struct audio_attributes_fields_t {
57    jfieldID  fieldUsage;        // AudioAttributes.mUsage
58    jfieldID  fieldContentType;  // AudioAttributes.mContentType
59    jfieldID  fieldFlags;        // AudioAttributes.mFlags
60    jfieldID  fieldFormattedTags;// AudioAttributes.mFormattedTags
61};
62static audio_track_fields_t      javaAudioTrackFields;
63static audio_attributes_fields_t javaAudioAttrFields;
64static PlaybackParams::fields_t gPlaybackParamsFields;
65
66struct audiotrack_callback_cookie {
67    jclass      audioTrack_class;
68    jobject     audioTrack_ref;
69    bool        busy;
70    Condition   cond;
71};
72
73// keep these values in sync with AudioTrack.java
74#define MODE_STATIC 0
75#define MODE_STREAM 1
76
77// ----------------------------------------------------------------------------
78class AudioTrackJniStorage {
79    public:
80        sp<MemoryHeapBase>         mMemHeap;
81        sp<MemoryBase>             mMemBase;
82        audiotrack_callback_cookie mCallbackData;
83        sp<JNIDeviceCallback>      mDeviceCallback;
84
85    AudioTrackJniStorage() {
86        mCallbackData.audioTrack_class = 0;
87        mCallbackData.audioTrack_ref = 0;
88    }
89
90    ~AudioTrackJniStorage() {
91        mMemBase.clear();
92        mMemHeap.clear();
93    }
94
95    bool allocSharedMem(int sizeInBytes) {
96        mMemHeap = new MemoryHeapBase(sizeInBytes, 0, "AudioTrack Heap Base");
97        if (mMemHeap->getHeapID() < 0) {
98            return false;
99        }
100        mMemBase = new MemoryBase(mMemHeap, 0, sizeInBytes);
101        return true;
102    }
103};
104
105static Mutex sLock;
106static SortedVector <audiotrack_callback_cookie *> sAudioTrackCallBackCookies;
107
108// ----------------------------------------------------------------------------
109#define DEFAULT_OUTPUT_SAMPLE_RATE   44100
110
111#define AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM         -16
112#define AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELMASK  -17
113#define AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT       -18
114#define AUDIOTRACK_ERROR_SETUP_INVALIDSTREAMTYPE   -19
115#define AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED    -20
116
117// ----------------------------------------------------------------------------
118static void audioCallback(int event, void* user, void *info) {
119
120    audiotrack_callback_cookie *callbackInfo = (audiotrack_callback_cookie *)user;
121    {
122        Mutex::Autolock l(sLock);
123        if (sAudioTrackCallBackCookies.indexOf(callbackInfo) < 0) {
124            return;
125        }
126        callbackInfo->busy = true;
127    }
128
129    switch (event) {
130    case AudioTrack::EVENT_MARKER: {
131        JNIEnv *env = AndroidRuntime::getJNIEnv();
132        if (user != NULL && env != NULL) {
133            env->CallStaticVoidMethod(
134                callbackInfo->audioTrack_class,
135                javaAudioTrackFields.postNativeEventInJava,
136                callbackInfo->audioTrack_ref, event, 0,0, NULL);
137            if (env->ExceptionCheck()) {
138                env->ExceptionDescribe();
139                env->ExceptionClear();
140            }
141        }
142        } break;
143
144    case AudioTrack::EVENT_NEW_POS: {
145        JNIEnv *env = AndroidRuntime::getJNIEnv();
146        if (user != NULL && env != NULL) {
147            env->CallStaticVoidMethod(
148                callbackInfo->audioTrack_class,
149                javaAudioTrackFields.postNativeEventInJava,
150                callbackInfo->audioTrack_ref, event, 0,0, NULL);
151            if (env->ExceptionCheck()) {
152                env->ExceptionDescribe();
153                env->ExceptionClear();
154            }
155        }
156        } break;
157    }
158
159    {
160        Mutex::Autolock l(sLock);
161        callbackInfo->busy = false;
162        callbackInfo->cond.broadcast();
163    }
164}
165
166
167// ----------------------------------------------------------------------------
168static sp<AudioTrack> getAudioTrack(JNIEnv* env, jobject thiz)
169{
170    Mutex::Autolock l(sLock);
171    AudioTrack* const at =
172            (AudioTrack*)env->GetLongField(thiz, javaAudioTrackFields.nativeTrackInJavaObj);
173    return sp<AudioTrack>(at);
174}
175
176static sp<AudioTrack> setAudioTrack(JNIEnv* env, jobject thiz, const sp<AudioTrack>& at)
177{
178    Mutex::Autolock l(sLock);
179    sp<AudioTrack> old =
180            (AudioTrack*)env->GetLongField(thiz, javaAudioTrackFields.nativeTrackInJavaObj);
181    if (at.get()) {
182        at->incStrong((void*)setAudioTrack);
183    }
184    if (old != 0) {
185        old->decStrong((void*)setAudioTrack);
186    }
187    env->SetLongField(thiz, javaAudioTrackFields.nativeTrackInJavaObj, (jlong)at.get());
188    return old;
189}
190
191// ----------------------------------------------------------------------------
192sp<AudioTrack> android_media_AudioTrack_getAudioTrack(JNIEnv* env, jobject audioTrackObj) {
193    return getAudioTrack(env, audioTrackObj);
194}
195
196// This function converts Java channel masks to a native channel mask.
197// validity should be checked with audio_is_output_channel().
198static inline audio_channel_mask_t nativeChannelMaskFromJavaChannelMasks(
199        jint channelPositionMask, jint channelIndexMask)
200{
201    if (channelIndexMask != 0) {  // channel index mask takes priority
202        // To convert to a native channel mask, the Java channel index mask
203        // requires adding the index representation.
204        return audio_channel_mask_from_representation_and_bits(
205                        AUDIO_CHANNEL_REPRESENTATION_INDEX,
206                        channelIndexMask);
207    }
208    // To convert to a native channel mask, the Java channel position mask
209    // requires a shift by 2 to skip the two deprecated channel
210    // configurations "default" and "mono".
211    return (audio_channel_mask_t)(channelPositionMask >> 2);
212}
213
214// ----------------------------------------------------------------------------
215static jint
216android_media_AudioTrack_setup(JNIEnv *env, jobject thiz, jobject weak_this,
217        jobject jaa,
218        jint sampleRateInHertz, jint channelPositionMask, jint channelIndexMask,
219        jint audioFormat, jint buffSizeInBytes, jint memoryMode, jintArray jSession) {
220
221    ALOGV("sampleRate=%d, channel mask=%x, index mask=%x, audioFormat(Java)=%d, buffSize=%d",
222        sampleRateInHertz, channelPositionMask, channelIndexMask, audioFormat, buffSizeInBytes);
223
224    if (jaa == 0) {
225        ALOGE("Error creating AudioTrack: invalid audio attributes");
226        return (jint) AUDIO_JAVA_ERROR;
227    }
228
229    // Invalid channel representations are caught by !audio_is_output_channel() below.
230    audio_channel_mask_t nativeChannelMask = nativeChannelMaskFromJavaChannelMasks(
231            channelPositionMask, channelIndexMask);
232    if (!audio_is_output_channel(nativeChannelMask)) {
233        ALOGE("Error creating AudioTrack: invalid native channel mask %#x.", nativeChannelMask);
234        return (jint) AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELMASK;
235    }
236
237    uint32_t channelCount = audio_channel_count_from_out_mask(nativeChannelMask);
238
239    // check the format.
240    // This function was called from Java, so we compare the format against the Java constants
241    audio_format_t format = audioFormatToNative(audioFormat);
242    if (format == AUDIO_FORMAT_INVALID) {
243        ALOGE("Error creating AudioTrack: unsupported audio format %d.", audioFormat);
244        return (jint) AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT;
245    }
246
247    // compute the frame count
248    size_t frameCount;
249    if (audio_is_linear_pcm(format)) {
250        const size_t bytesPerSample = audio_bytes_per_sample(format);
251        frameCount = buffSizeInBytes / (channelCount * bytesPerSample);
252    } else {
253        frameCount = buffSizeInBytes;
254    }
255
256    jclass clazz = env->GetObjectClass(thiz);
257    if (clazz == NULL) {
258        ALOGE("Can't find %s when setting up callback.", kClassPathName);
259        return (jint) AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED;
260    }
261
262    if (jSession == NULL) {
263        ALOGE("Error creating AudioTrack: invalid session ID pointer");
264        return (jint) AUDIO_JAVA_ERROR;
265    }
266
267    jint* nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL);
268    if (nSession == NULL) {
269        ALOGE("Error creating AudioTrack: Error retrieving session id pointer");
270        return (jint) AUDIO_JAVA_ERROR;
271    }
272    int sessionId = nSession[0];
273    env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
274    nSession = NULL;
275
276    // create the native AudioTrack object
277    sp<AudioTrack> lpTrack = new AudioTrack();
278
279    audio_attributes_t *paa = NULL;
280    // read the AudioAttributes values
281    paa = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
282    const jstring jtags =
283            (jstring) env->GetObjectField(jaa, javaAudioAttrFields.fieldFormattedTags);
284    const char* tags = env->GetStringUTFChars(jtags, NULL);
285    // copying array size -1, char array for tags was calloc'd, no need to NULL-terminate it
286    strncpy(paa->tags, tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
287    env->ReleaseStringUTFChars(jtags, tags);
288    paa->usage = (audio_usage_t) env->GetIntField(jaa, javaAudioAttrFields.fieldUsage);
289    paa->content_type =
290            (audio_content_type_t) env->GetIntField(jaa, javaAudioAttrFields.fieldContentType);
291    paa->flags = env->GetIntField(jaa, javaAudioAttrFields.fieldFlags);
292
293    ALOGV("AudioTrack_setup for usage=%d content=%d flags=0x%#x tags=%s",
294            paa->usage, paa->content_type, paa->flags, paa->tags);
295
296    // initialize the callback information:
297    // this data will be passed with every AudioTrack callback
298    AudioTrackJniStorage* lpJniStorage = new AudioTrackJniStorage();
299    lpJniStorage->mCallbackData.audioTrack_class = (jclass)env->NewGlobalRef(clazz);
300    // we use a weak reference so the AudioTrack object can be garbage collected.
301    lpJniStorage->mCallbackData.audioTrack_ref = env->NewGlobalRef(weak_this);
302    lpJniStorage->mCallbackData.busy = false;
303
304    // initialize the native AudioTrack object
305    status_t status = NO_ERROR;
306    switch (memoryMode) {
307    case MODE_STREAM:
308
309        status = lpTrack->set(
310                AUDIO_STREAM_DEFAULT,// stream type, but more info conveyed in paa (last argument)
311                sampleRateInHertz,
312                format,// word length, PCM
313                nativeChannelMask,
314                frameCount,
315                AUDIO_OUTPUT_FLAG_NONE,
316                audioCallback, &(lpJniStorage->mCallbackData),//callback, callback data (user)
317                0,// notificationFrames == 0 since not using EVENT_MORE_DATA to feed the AudioTrack
318                0,// shared mem
319                true,// thread can call Java
320                sessionId,// audio session ID
321                AudioTrack::TRANSFER_SYNC,
322                NULL,                         // default offloadInfo
323                -1, -1,                       // default uid, pid values
324                paa);
325        break;
326
327    case MODE_STATIC:
328        // AudioTrack is using shared memory
329
330        if (!lpJniStorage->allocSharedMem(buffSizeInBytes)) {
331            ALOGE("Error creating AudioTrack in static mode: error creating mem heap base");
332            goto native_init_failure;
333        }
334
335        status = lpTrack->set(
336                AUDIO_STREAM_DEFAULT,// stream type, but more info conveyed in paa (last argument)
337                sampleRateInHertz,
338                format,// word length, PCM
339                nativeChannelMask,
340                frameCount,
341                AUDIO_OUTPUT_FLAG_NONE,
342                audioCallback, &(lpJniStorage->mCallbackData),//callback, callback data (user));
343                0,// notificationFrames == 0 since not using EVENT_MORE_DATA to feed the AudioTrack
344                lpJniStorage->mMemBase,// shared mem
345                true,// thread can call Java
346                sessionId,// audio session ID
347                AudioTrack::TRANSFER_SHARED,
348                NULL,                         // default offloadInfo
349                -1, -1,                       // default uid, pid values
350                paa);
351        break;
352
353    default:
354        ALOGE("Unknown mode %d", memoryMode);
355        goto native_init_failure;
356    }
357
358    if (status != NO_ERROR) {
359        ALOGE("Error %d initializing AudioTrack", status);
360        goto native_init_failure;
361    }
362
363    nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL);
364    if (nSession == NULL) {
365        ALOGE("Error creating AudioTrack: Error retrieving session id pointer");
366        goto native_init_failure;
367    }
368    // read the audio session ID back from AudioTrack in case we create a new session
369    nSession[0] = lpTrack->getSessionId();
370    env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
371    nSession = NULL;
372
373    {   // scope for the lock
374        Mutex::Autolock l(sLock);
375        sAudioTrackCallBackCookies.add(&lpJniStorage->mCallbackData);
376    }
377    // save our newly created C++ AudioTrack in the "nativeTrackInJavaObj" field
378    // of the Java object (in mNativeTrackInJavaObj)
379    setAudioTrack(env, thiz, lpTrack);
380
381    // save the JNI resources so we can free them later
382    //ALOGV("storing lpJniStorage: %x\n", (long)lpJniStorage);
383    env->SetLongField(thiz, javaAudioTrackFields.jniData, (jlong)lpJniStorage);
384
385    // since we had audio attributes, the stream type was derived from them during the
386    // creation of the native AudioTrack: push the same value to the Java object
387    env->SetIntField(thiz, javaAudioTrackFields.fieldStreamType, (jint) lpTrack->streamType());
388    // audio attributes were copied in AudioTrack creation
389    free(paa);
390    paa = NULL;
391
392
393    return (jint) AUDIO_JAVA_SUCCESS;
394
395    // failures:
396native_init_failure:
397    if (paa != NULL) {
398        free(paa);
399    }
400    if (nSession != NULL) {
401        env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
402    }
403    env->DeleteGlobalRef(lpJniStorage->mCallbackData.audioTrack_class);
404    env->DeleteGlobalRef(lpJniStorage->mCallbackData.audioTrack_ref);
405    delete lpJniStorage;
406    env->SetLongField(thiz, javaAudioTrackFields.jniData, 0);
407
408    return (jint) AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED;
409}
410
411
412// ----------------------------------------------------------------------------
413static void
414android_media_AudioTrack_start(JNIEnv *env, jobject thiz)
415{
416    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
417    if (lpTrack == NULL) {
418        jniThrowException(env, "java/lang/IllegalStateException",
419            "Unable to retrieve AudioTrack pointer for start()");
420        return;
421    }
422
423    lpTrack->start();
424}
425
426
427// ----------------------------------------------------------------------------
428static void
429android_media_AudioTrack_stop(JNIEnv *env, jobject thiz)
430{
431    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
432    if (lpTrack == NULL) {
433        jniThrowException(env, "java/lang/IllegalStateException",
434            "Unable to retrieve AudioTrack pointer for stop()");
435        return;
436    }
437
438    lpTrack->stop();
439}
440
441
442// ----------------------------------------------------------------------------
443static void
444android_media_AudioTrack_pause(JNIEnv *env, jobject thiz)
445{
446    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
447    if (lpTrack == NULL) {
448        jniThrowException(env, "java/lang/IllegalStateException",
449            "Unable to retrieve AudioTrack pointer for pause()");
450        return;
451    }
452
453    lpTrack->pause();
454}
455
456
457// ----------------------------------------------------------------------------
458static void
459android_media_AudioTrack_flush(JNIEnv *env, jobject thiz)
460{
461    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
462    if (lpTrack == NULL) {
463        jniThrowException(env, "java/lang/IllegalStateException",
464            "Unable to retrieve AudioTrack pointer for flush()");
465        return;
466    }
467
468    lpTrack->flush();
469}
470
471// ----------------------------------------------------------------------------
472static void
473android_media_AudioTrack_set_volume(JNIEnv *env, jobject thiz, jfloat leftVol, jfloat rightVol )
474{
475    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
476    if (lpTrack == NULL) {
477        jniThrowException(env, "java/lang/IllegalStateException",
478            "Unable to retrieve AudioTrack pointer for setVolume()");
479        return;
480    }
481
482    lpTrack->setVolume(leftVol, rightVol);
483}
484
485// ----------------------------------------------------------------------------
486
487#define CALLBACK_COND_WAIT_TIMEOUT_MS 1000
488static void android_media_AudioTrack_release(JNIEnv *env,  jobject thiz) {
489    sp<AudioTrack> lpTrack = setAudioTrack(env, thiz, 0);
490    if (lpTrack == NULL) {
491        return;
492    }
493    //ALOGV("deleting lpTrack: %x\n", (int)lpTrack);
494    lpTrack->stop();
495
496    // delete the JNI data
497    AudioTrackJniStorage* pJniStorage = (AudioTrackJniStorage *)env->GetLongField(
498        thiz, javaAudioTrackFields.jniData);
499    // reset the native resources in the Java object so any attempt to access
500    // them after a call to release fails.
501    env->SetLongField(thiz, javaAudioTrackFields.jniData, 0);
502
503    if (pJniStorage) {
504        Mutex::Autolock l(sLock);
505        audiotrack_callback_cookie *lpCookie = &pJniStorage->mCallbackData;
506        //ALOGV("deleting pJniStorage: %x\n", (int)pJniStorage);
507        while (lpCookie->busy) {
508            if (lpCookie->cond.waitRelative(sLock,
509                                            milliseconds(CALLBACK_COND_WAIT_TIMEOUT_MS)) !=
510                                                    NO_ERROR) {
511                break;
512            }
513        }
514        sAudioTrackCallBackCookies.remove(lpCookie);
515        // delete global refs created in native_setup
516        env->DeleteGlobalRef(lpCookie->audioTrack_class);
517        env->DeleteGlobalRef(lpCookie->audioTrack_ref);
518        delete pJniStorage;
519    }
520}
521
522
523// ----------------------------------------------------------------------------
524static void android_media_AudioTrack_finalize(JNIEnv *env,  jobject thiz) {
525    //ALOGV("android_media_AudioTrack_finalize jobject: %x\n", (int)thiz);
526    android_media_AudioTrack_release(env, thiz);
527}
528
529// overloaded JNI array helper functions (same as in android_media_AudioRecord)
530static inline
531jbyte *envGetArrayElements(JNIEnv *env, jbyteArray array, jboolean *isCopy) {
532    return env->GetByteArrayElements(array, isCopy);
533}
534
535static inline
536void envReleaseArrayElements(JNIEnv *env, jbyteArray array, jbyte *elems, jint mode) {
537    env->ReleaseByteArrayElements(array, elems, mode);
538}
539
540static inline
541jshort *envGetArrayElements(JNIEnv *env, jshortArray array, jboolean *isCopy) {
542    return env->GetShortArrayElements(array, isCopy);
543}
544
545static inline
546void envReleaseArrayElements(JNIEnv *env, jshortArray array, jshort *elems, jint mode) {
547    env->ReleaseShortArrayElements(array, elems, mode);
548}
549
550static inline
551jfloat *envGetArrayElements(JNIEnv *env, jfloatArray array, jboolean *isCopy) {
552    return env->GetFloatArrayElements(array, isCopy);
553}
554
555static inline
556void envReleaseArrayElements(JNIEnv *env, jfloatArray array, jfloat *elems, jint mode) {
557    env->ReleaseFloatArrayElements(array, elems, mode);
558}
559
560// ----------------------------------------------------------------------------
561template <typename T>
562static jint writeToTrack(const sp<AudioTrack>& track, jint audioFormat, const T *data,
563                         jint offsetInSamples, jint sizeInSamples, bool blocking) {
564    // give the data to the native AudioTrack object (the data starts at the offset)
565    ssize_t written = 0;
566    // regular write() or copy the data to the AudioTrack's shared memory?
567    size_t sizeInBytes = sizeInSamples * sizeof(T);
568    if (track->sharedBuffer() == 0) {
569        written = track->write(data + offsetInSamples, sizeInBytes, blocking);
570        // for compatibility with earlier behavior of write(), return 0 in this case
571        if (written == (ssize_t) WOULD_BLOCK) {
572            written = 0;
573        }
574    } else {
575        // writing to shared memory, check for capacity
576        if ((size_t)sizeInBytes > track->sharedBuffer()->size()) {
577            sizeInBytes = track->sharedBuffer()->size();
578        }
579        memcpy(track->sharedBuffer()->pointer(), data + offsetInSamples, sizeInBytes);
580        written = sizeInBytes;
581    }
582    if (written > 0) {
583        return written / sizeof(T);
584    }
585    // for compatibility, error codes pass through unchanged
586    return written;
587}
588
589// ----------------------------------------------------------------------------
590template <typename T>
591static jint android_media_AudioTrack_writeArray(JNIEnv *env, jobject thiz,
592                                                T javaAudioData,
593                                                jint offsetInSamples, jint sizeInSamples,
594                                                jint javaAudioFormat,
595                                                jboolean isWriteBlocking) {
596    //ALOGV("android_media_AudioTrack_writeArray(offset=%d, sizeInSamples=%d) called",
597    //        offsetInSamples, sizeInSamples);
598    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
599    if (lpTrack == NULL) {
600        jniThrowException(env, "java/lang/IllegalStateException",
601            "Unable to retrieve AudioTrack pointer for write()");
602        return (jint)AUDIO_JAVA_INVALID_OPERATION;
603    }
604
605    if (javaAudioData == NULL) {
606        ALOGE("NULL java array of audio data to play");
607        return (jint)AUDIO_JAVA_BAD_VALUE;
608    }
609
610    // NOTE: We may use GetPrimitiveArrayCritical() when the JNI implementation changes in such
611    // a way that it becomes much more efficient. When doing so, we will have to prevent the
612    // AudioSystem callback to be called while in critical section (in case of media server
613    // process crash for instance)
614
615    // get the pointer for the audio data from the java array
616    auto cAudioData = envGetArrayElements(env, javaAudioData, NULL);
617    if (cAudioData == NULL) {
618        ALOGE("Error retrieving source of audio data to play");
619        return (jint)AUDIO_JAVA_BAD_VALUE; // out of memory or no data to load
620    }
621
622    jint samplesWritten = writeToTrack(lpTrack, javaAudioFormat, cAudioData,
623            offsetInSamples, sizeInSamples, isWriteBlocking == JNI_TRUE /* blocking */);
624
625    envReleaseArrayElements(env, javaAudioData, cAudioData, 0);
626
627    //ALOGV("write wrote %d (tried %d) samples in the native AudioTrack with offset %d",
628    //        (int)samplesWritten, (int)(sizeInSamples), (int)offsetInSamples);
629    return samplesWritten;
630}
631
632// ----------------------------------------------------------------------------
633static jint android_media_AudioTrack_write_native_bytes(JNIEnv *env,  jobject thiz,
634        jbyteArray javaBytes, jint byteOffset, jint sizeInBytes,
635        jint javaAudioFormat, jboolean isWriteBlocking) {
636    //ALOGV("android_media_AudioTrack_write_native_bytes(offset=%d, sizeInBytes=%d) called",
637    //    offsetInBytes, sizeInBytes);
638    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
639    if (lpTrack == NULL) {
640        jniThrowException(env, "java/lang/IllegalStateException",
641                "Unable to retrieve AudioTrack pointer for write()");
642        return (jint)AUDIO_JAVA_INVALID_OPERATION;
643    }
644
645    ScopedBytesRO bytes(env, javaBytes);
646    if (bytes.get() == NULL) {
647        ALOGE("Error retrieving source of audio data to play, can't play");
648        return (jint)AUDIO_JAVA_BAD_VALUE;
649    }
650
651    jint written = writeToTrack(lpTrack, javaAudioFormat, bytes.get(), byteOffset,
652            sizeInBytes, isWriteBlocking == JNI_TRUE /* blocking */);
653
654    return written;
655}
656
657// ----------------------------------------------------------------------------
658static jint android_media_AudioTrack_get_native_frame_count(JNIEnv *env,  jobject thiz) {
659    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
660    if (lpTrack == NULL) {
661        jniThrowException(env, "java/lang/IllegalStateException",
662            "Unable to retrieve AudioTrack pointer for frameCount()");
663        return (jint)AUDIO_JAVA_ERROR;
664    }
665
666    return lpTrack->frameCount();
667}
668
669
670// ----------------------------------------------------------------------------
671static jint android_media_AudioTrack_set_playback_rate(JNIEnv *env,  jobject thiz,
672        jint sampleRateInHz) {
673    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
674    if (lpTrack == NULL) {
675        jniThrowException(env, "java/lang/IllegalStateException",
676            "Unable to retrieve AudioTrack pointer for setSampleRate()");
677        return (jint)AUDIO_JAVA_ERROR;
678    }
679    return nativeToJavaStatus(lpTrack->setSampleRate(sampleRateInHz));
680}
681
682
683// ----------------------------------------------------------------------------
684static jint android_media_AudioTrack_get_playback_rate(JNIEnv *env,  jobject thiz) {
685    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
686    if (lpTrack == NULL) {
687        jniThrowException(env, "java/lang/IllegalStateException",
688            "Unable to retrieve AudioTrack pointer for getSampleRate()");
689        return (jint)AUDIO_JAVA_ERROR;
690    }
691    return (jint) lpTrack->getSampleRate();
692}
693
694
695// ----------------------------------------------------------------------------
696static void android_media_AudioTrack_set_playback_params(JNIEnv *env,  jobject thiz,
697        jobject params) {
698    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
699    if (lpTrack == NULL) {
700        jniThrowException(env, "java/lang/IllegalStateException",
701            "AudioTrack not initialized");
702        return;
703    }
704
705    PlaybackParams pbp;
706    pbp.fillFromJobject(env, gPlaybackParamsFields, params);
707
708    ALOGV("setPlaybackParams: %d:%f %d:%f %d:%u %d:%u",
709            pbp.speedSet, pbp.audioRate.mSpeed,
710            pbp.pitchSet, pbp.audioRate.mPitch,
711            pbp.audioFallbackModeSet, pbp.audioRate.mFallbackMode,
712            pbp.audioStretchModeSet, pbp.audioRate.mStretchMode);
713
714    // to simulate partially set params, we do a read-modify-write.
715    // TODO: pass in the valid set mask into AudioTrack.
716    AudioPlaybackRate rate = lpTrack->getPlaybackRate();
717    bool updatedRate = false;
718    if (pbp.speedSet) {
719        rate.mSpeed = pbp.audioRate.mSpeed;
720        updatedRate = true;
721    }
722    if (pbp.pitchSet) {
723        rate.mPitch = pbp.audioRate.mPitch;
724        updatedRate = true;
725    }
726    if (pbp.audioFallbackModeSet) {
727        rate.mFallbackMode = pbp.audioRate.mFallbackMode;
728        updatedRate = true;
729    }
730    if (pbp.audioStretchModeSet) {
731        rate.mStretchMode = pbp.audioRate.mStretchMode;
732        updatedRate = true;
733    }
734    if (updatedRate) {
735        if (lpTrack->setPlaybackRate(rate) != OK) {
736            jniThrowException(env, "java/lang/IllegalArgumentException",
737                    "arguments out of range");
738        }
739    }
740}
741
742
743// ----------------------------------------------------------------------------
744static jobject android_media_AudioTrack_get_playback_params(JNIEnv *env,  jobject thiz,
745        jobject params) {
746    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
747    if (lpTrack == NULL) {
748        jniThrowException(env, "java/lang/IllegalStateException",
749            "AudioTrack not initialized");
750        return NULL;
751    }
752
753    PlaybackParams pbs;
754    pbs.audioRate = lpTrack->getPlaybackRate();
755    pbs.speedSet = true;
756    pbs.pitchSet = true;
757    pbs.audioFallbackModeSet = true;
758    pbs.audioStretchModeSet = true;
759    return pbs.asJobject(env, gPlaybackParamsFields);
760}
761
762
763// ----------------------------------------------------------------------------
764static jint android_media_AudioTrack_set_marker_pos(JNIEnv *env,  jobject thiz,
765        jint markerPos) {
766    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
767    if (lpTrack == NULL) {
768        jniThrowException(env, "java/lang/IllegalStateException",
769            "Unable to retrieve AudioTrack pointer for setMarkerPosition()");
770        return (jint)AUDIO_JAVA_ERROR;
771    }
772    return nativeToJavaStatus( lpTrack->setMarkerPosition(markerPos) );
773}
774
775
776// ----------------------------------------------------------------------------
777static jint android_media_AudioTrack_get_marker_pos(JNIEnv *env,  jobject thiz) {
778    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
779    uint32_t markerPos = 0;
780
781    if (lpTrack == NULL) {
782        jniThrowException(env, "java/lang/IllegalStateException",
783            "Unable to retrieve AudioTrack pointer for getMarkerPosition()");
784        return (jint)AUDIO_JAVA_ERROR;
785    }
786    lpTrack->getMarkerPosition(&markerPos);
787    return (jint)markerPos;
788}
789
790
791// ----------------------------------------------------------------------------
792static jint android_media_AudioTrack_set_pos_update_period(JNIEnv *env,  jobject thiz,
793        jint period) {
794    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
795    if (lpTrack == NULL) {
796        jniThrowException(env, "java/lang/IllegalStateException",
797            "Unable to retrieve AudioTrack pointer for setPositionUpdatePeriod()");
798        return (jint)AUDIO_JAVA_ERROR;
799    }
800    return nativeToJavaStatus( lpTrack->setPositionUpdatePeriod(period) );
801}
802
803
804// ----------------------------------------------------------------------------
805static jint android_media_AudioTrack_get_pos_update_period(JNIEnv *env,  jobject thiz) {
806    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
807    uint32_t period = 0;
808
809    if (lpTrack == NULL) {
810        jniThrowException(env, "java/lang/IllegalStateException",
811            "Unable to retrieve AudioTrack pointer for getPositionUpdatePeriod()");
812        return (jint)AUDIO_JAVA_ERROR;
813    }
814    lpTrack->getPositionUpdatePeriod(&period);
815    return (jint)period;
816}
817
818
819// ----------------------------------------------------------------------------
820static jint android_media_AudioTrack_set_position(JNIEnv *env,  jobject thiz,
821        jint position) {
822    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
823    if (lpTrack == NULL) {
824        jniThrowException(env, "java/lang/IllegalStateException",
825            "Unable to retrieve AudioTrack pointer for setPosition()");
826        return (jint)AUDIO_JAVA_ERROR;
827    }
828    return nativeToJavaStatus( lpTrack->setPosition(position) );
829}
830
831
832// ----------------------------------------------------------------------------
833static jint android_media_AudioTrack_get_position(JNIEnv *env,  jobject thiz) {
834    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
835    uint32_t position = 0;
836
837    if (lpTrack == NULL) {
838        jniThrowException(env, "java/lang/IllegalStateException",
839            "Unable to retrieve AudioTrack pointer for getPosition()");
840        return (jint)AUDIO_JAVA_ERROR;
841    }
842    lpTrack->getPosition(&position);
843    return (jint)position;
844}
845
846
847// ----------------------------------------------------------------------------
848static jint android_media_AudioTrack_get_latency(JNIEnv *env,  jobject thiz) {
849    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
850
851    if (lpTrack == NULL) {
852        jniThrowException(env, "java/lang/IllegalStateException",
853            "Unable to retrieve AudioTrack pointer for latency()");
854        return (jint)AUDIO_JAVA_ERROR;
855    }
856    return (jint)lpTrack->latency();
857}
858
859
860// ----------------------------------------------------------------------------
861static jint android_media_AudioTrack_get_timestamp(JNIEnv *env,  jobject thiz, jlongArray jTimestamp) {
862    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
863
864    if (lpTrack == NULL) {
865        ALOGE("Unable to retrieve AudioTrack pointer for getTimestamp()");
866        return (jint)AUDIO_JAVA_ERROR;
867    }
868    AudioTimestamp timestamp;
869    status_t status = lpTrack->getTimestamp(timestamp);
870    if (status == OK) {
871        jlong* nTimestamp = (jlong *) env->GetPrimitiveArrayCritical(jTimestamp, NULL);
872        if (nTimestamp == NULL) {
873            ALOGE("Unable to get array for getTimestamp()");
874            return (jint)AUDIO_JAVA_ERROR;
875        }
876        nTimestamp[0] = (jlong) timestamp.mPosition;
877        nTimestamp[1] = (jlong) ((timestamp.mTime.tv_sec * 1000000000LL) + timestamp.mTime.tv_nsec);
878        env->ReleasePrimitiveArrayCritical(jTimestamp, nTimestamp, 0);
879    }
880    return (jint) nativeToJavaStatus(status);
881}
882
883
884// ----------------------------------------------------------------------------
885static jint android_media_AudioTrack_set_loop(JNIEnv *env,  jobject thiz,
886        jint loopStart, jint loopEnd, jint loopCount) {
887    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
888    if (lpTrack == NULL) {
889        jniThrowException(env, "java/lang/IllegalStateException",
890            "Unable to retrieve AudioTrack pointer for setLoop()");
891        return (jint)AUDIO_JAVA_ERROR;
892    }
893    return nativeToJavaStatus( lpTrack->setLoop(loopStart, loopEnd, loopCount) );
894}
895
896
897// ----------------------------------------------------------------------------
898static jint android_media_AudioTrack_reload(JNIEnv *env,  jobject thiz) {
899    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
900    if (lpTrack == NULL) {
901        jniThrowException(env, "java/lang/IllegalStateException",
902            "Unable to retrieve AudioTrack pointer for reload()");
903        return (jint)AUDIO_JAVA_ERROR;
904    }
905    return nativeToJavaStatus( lpTrack->reload() );
906}
907
908
909// ----------------------------------------------------------------------------
910static jint android_media_AudioTrack_get_output_sample_rate(JNIEnv *env,  jobject thiz,
911        jint javaStreamType) {
912    uint32_t afSamplingRate;
913    // convert the stream type from Java to native value
914    // FIXME: code duplication with android_media_AudioTrack_setup()
915    audio_stream_type_t nativeStreamType;
916    switch (javaStreamType) {
917    case AUDIO_STREAM_VOICE_CALL:
918    case AUDIO_STREAM_SYSTEM:
919    case AUDIO_STREAM_RING:
920    case AUDIO_STREAM_MUSIC:
921    case AUDIO_STREAM_ALARM:
922    case AUDIO_STREAM_NOTIFICATION:
923    case AUDIO_STREAM_BLUETOOTH_SCO:
924    case AUDIO_STREAM_DTMF:
925        nativeStreamType = (audio_stream_type_t) javaStreamType;
926        break;
927    default:
928        nativeStreamType = AUDIO_STREAM_DEFAULT;
929        break;
930    }
931
932    status_t status = AudioSystem::getOutputSamplingRate(&afSamplingRate, nativeStreamType);
933    if (status != NO_ERROR) {
934        ALOGE("Error %d in AudioSystem::getOutputSamplingRate() for stream type %d "
935              "in AudioTrack JNI", status, nativeStreamType);
936        return DEFAULT_OUTPUT_SAMPLE_RATE;
937    } else {
938        return afSamplingRate;
939    }
940}
941
942
943// ----------------------------------------------------------------------------
944// returns the minimum required size for the successful creation of a streaming AudioTrack
945// returns -1 if there was an error querying the hardware.
946static jint android_media_AudioTrack_get_min_buff_size(JNIEnv *env,  jobject thiz,
947    jint sampleRateInHertz, jint channelCount, jint audioFormat) {
948
949    size_t frameCount;
950    const status_t status = AudioTrack::getMinFrameCount(&frameCount, AUDIO_STREAM_DEFAULT,
951            sampleRateInHertz);
952    if (status != NO_ERROR) {
953        ALOGE("AudioTrack::getMinFrameCount() for sample rate %d failed with status %d",
954                sampleRateInHertz, status);
955        return -1;
956    }
957    const audio_format_t format = audioFormatToNative(audioFormat);
958    if (audio_is_linear_pcm(format)) {
959        const size_t bytesPerSample = audio_bytes_per_sample(format);
960        return frameCount * channelCount * bytesPerSample;
961    } else {
962        return frameCount;
963    }
964}
965
966// ----------------------------------------------------------------------------
967static jint
968android_media_AudioTrack_setAuxEffectSendLevel(JNIEnv *env, jobject thiz, jfloat level )
969{
970    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
971    if (lpTrack == NULL ) {
972        jniThrowException(env, "java/lang/IllegalStateException",
973            "Unable to retrieve AudioTrack pointer for setAuxEffectSendLevel()");
974        return -1;
975    }
976
977    status_t status = lpTrack->setAuxEffectSendLevel(level);
978    if (status != NO_ERROR) {
979        ALOGE("AudioTrack::setAuxEffectSendLevel() for level %g failed with status %d",
980                level, status);
981    }
982    return (jint) status;
983}
984
985// ----------------------------------------------------------------------------
986static jint android_media_AudioTrack_attachAuxEffect(JNIEnv *env,  jobject thiz,
987        jint effectId) {
988    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
989    if (lpTrack == NULL) {
990        jniThrowException(env, "java/lang/IllegalStateException",
991            "Unable to retrieve AudioTrack pointer for attachAuxEffect()");
992        return (jint)AUDIO_JAVA_ERROR;
993    }
994    return nativeToJavaStatus( lpTrack->attachAuxEffect(effectId) );
995}
996
997static jboolean android_media_AudioTrack_setOutputDevice(
998                JNIEnv *env,  jobject thiz, jint device_id) {
999
1000    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
1001    return lpTrack->setOutputDevice(device_id) == NO_ERROR;
1002}
1003
1004static jint android_media_AudioTrack_getRoutedDeviceId(
1005                JNIEnv *env,  jobject thiz) {
1006
1007    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
1008    if (lpTrack == NULL) {
1009        return 0;
1010    }
1011    return (jint)lpTrack->getRoutedDeviceId();
1012}
1013
1014static void android_media_AudioTrack_enableDeviceCallback(
1015                JNIEnv *env,  jobject thiz) {
1016
1017    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
1018    if (lpTrack == NULL) {
1019        return;
1020    }
1021    AudioTrackJniStorage* pJniStorage = (AudioTrackJniStorage *)env->GetLongField(
1022        thiz, javaAudioTrackFields.jniData);
1023    if (pJniStorage == NULL || pJniStorage->mDeviceCallback != 0) {
1024        return;
1025    }
1026    pJniStorage->mDeviceCallback =
1027    new JNIDeviceCallback(env, thiz, pJniStorage->mCallbackData.audioTrack_ref,
1028                          javaAudioTrackFields.postNativeEventInJava);
1029    lpTrack->addAudioDeviceCallback(pJniStorage->mDeviceCallback);
1030}
1031
1032static void android_media_AudioTrack_disableDeviceCallback(
1033                JNIEnv *env,  jobject thiz) {
1034
1035    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
1036    if (lpTrack == NULL) {
1037        return;
1038    }
1039    AudioTrackJniStorage* pJniStorage = (AudioTrackJniStorage *)env->GetLongField(
1040        thiz, javaAudioTrackFields.jniData);
1041    if (pJniStorage == NULL || pJniStorage->mDeviceCallback == 0) {
1042        return;
1043    }
1044    lpTrack->removeAudioDeviceCallback(pJniStorage->mDeviceCallback);
1045    pJniStorage->mDeviceCallback.clear();
1046}
1047
1048
1049// ----------------------------------------------------------------------------
1050// ----------------------------------------------------------------------------
1051static JNINativeMethod gMethods[] = {
1052    // name,              signature,     funcPtr
1053    {"native_start",         "()V",      (void *)android_media_AudioTrack_start},
1054    {"native_stop",          "()V",      (void *)android_media_AudioTrack_stop},
1055    {"native_pause",         "()V",      (void *)android_media_AudioTrack_pause},
1056    {"native_flush",         "()V",      (void *)android_media_AudioTrack_flush},
1057    {"native_setup",     "(Ljava/lang/Object;Ljava/lang/Object;IIIIII[I)I",
1058                                         (void *)android_media_AudioTrack_setup},
1059    {"native_finalize",      "()V",      (void *)android_media_AudioTrack_finalize},
1060    {"native_release",       "()V",      (void *)android_media_AudioTrack_release},
1061    {"native_write_byte",    "([BIIIZ)I",(void *)android_media_AudioTrack_writeArray<jbyteArray>},
1062    {"native_write_native_bytes",
1063                             "(Ljava/lang/Object;IIIZ)I",
1064                                         (void *)android_media_AudioTrack_write_native_bytes},
1065    {"native_write_short",   "([SIIIZ)I",(void *)android_media_AudioTrack_writeArray<jshortArray>},
1066    {"native_write_float",   "([FIIIZ)I",(void *)android_media_AudioTrack_writeArray<jfloatArray>},
1067    {"native_setVolume",     "(FF)V",    (void *)android_media_AudioTrack_set_volume},
1068    {"native_get_native_frame_count",
1069                             "()I",      (void *)android_media_AudioTrack_get_native_frame_count},
1070    {"native_set_playback_rate",
1071                             "(I)I",     (void *)android_media_AudioTrack_set_playback_rate},
1072    {"native_get_playback_rate",
1073                             "()I",      (void *)android_media_AudioTrack_get_playback_rate},
1074    {"native_set_playback_params",
1075                             "(Landroid/media/PlaybackParams;)V",
1076                                         (void *)android_media_AudioTrack_set_playback_params},
1077    {"native_get_playback_params",
1078                             "()Landroid/media/PlaybackParams;",
1079                                         (void *)android_media_AudioTrack_get_playback_params},
1080    {"native_set_marker_pos","(I)I",     (void *)android_media_AudioTrack_set_marker_pos},
1081    {"native_get_marker_pos","()I",      (void *)android_media_AudioTrack_get_marker_pos},
1082    {"native_set_pos_update_period",
1083                             "(I)I",     (void *)android_media_AudioTrack_set_pos_update_period},
1084    {"native_get_pos_update_period",
1085                             "()I",      (void *)android_media_AudioTrack_get_pos_update_period},
1086    {"native_set_position",  "(I)I",     (void *)android_media_AudioTrack_set_position},
1087    {"native_get_position",  "()I",      (void *)android_media_AudioTrack_get_position},
1088    {"native_get_latency",   "()I",      (void *)android_media_AudioTrack_get_latency},
1089    {"native_get_timestamp", "([J)I",    (void *)android_media_AudioTrack_get_timestamp},
1090    {"native_set_loop",      "(III)I",   (void *)android_media_AudioTrack_set_loop},
1091    {"native_reload_static", "()I",      (void *)android_media_AudioTrack_reload},
1092    {"native_get_output_sample_rate",
1093                             "(I)I",      (void *)android_media_AudioTrack_get_output_sample_rate},
1094    {"native_get_min_buff_size",
1095                             "(III)I",   (void *)android_media_AudioTrack_get_min_buff_size},
1096    {"native_setAuxEffectSendLevel",
1097                             "(F)I",     (void *)android_media_AudioTrack_setAuxEffectSendLevel},
1098    {"native_attachAuxEffect",
1099                             "(I)I",     (void *)android_media_AudioTrack_attachAuxEffect},
1100    {"native_setOutputDevice", "(I)Z",
1101                             (void *)android_media_AudioTrack_setOutputDevice},
1102    {"native_getRoutedDeviceId", "()I", (void *)android_media_AudioTrack_getRoutedDeviceId},
1103    {"native_enableDeviceCallback", "()V", (void *)android_media_AudioTrack_enableDeviceCallback},
1104    {"native_disableDeviceCallback", "()V", (void *)android_media_AudioTrack_disableDeviceCallback},
1105};
1106
1107
1108// field names found in android/media/AudioTrack.java
1109#define JAVA_POSTEVENT_CALLBACK_NAME                    "postEventFromNative"
1110#define JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME            "mNativeTrackInJavaObj"
1111#define JAVA_JNIDATA_FIELD_NAME                         "mJniData"
1112#define JAVA_STREAMTYPE_FIELD_NAME                      "mStreamType"
1113
1114// ----------------------------------------------------------------------------
1115// preconditions:
1116//    theClass is valid
1117bool android_media_getIntConstantFromClass(JNIEnv* pEnv, jclass theClass, const char* className,
1118                             const char* constName, int* constVal) {
1119    jfieldID javaConst = NULL;
1120    javaConst = pEnv->GetStaticFieldID(theClass, constName, "I");
1121    if (javaConst != NULL) {
1122        *constVal = pEnv->GetStaticIntField(theClass, javaConst);
1123        return true;
1124    } else {
1125        ALOGE("Can't find %s.%s", className, constName);
1126        return false;
1127    }
1128}
1129
1130
1131// ----------------------------------------------------------------------------
1132int register_android_media_AudioTrack(JNIEnv *env)
1133{
1134    javaAudioTrackFields.nativeTrackInJavaObj = NULL;
1135    javaAudioTrackFields.postNativeEventInJava = NULL;
1136
1137    // Get the AudioTrack class
1138    jclass audioTrackClass = FindClassOrDie(env, kClassPathName);
1139
1140    // Get the postEvent method
1141    javaAudioTrackFields.postNativeEventInJava = GetStaticMethodIDOrDie(env,
1142            audioTrackClass, JAVA_POSTEVENT_CALLBACK_NAME,
1143            "(Ljava/lang/Object;IIILjava/lang/Object;)V");
1144
1145    // Get the variables fields
1146    //      nativeTrackInJavaObj
1147    javaAudioTrackFields.nativeTrackInJavaObj = GetFieldIDOrDie(env,
1148            audioTrackClass, JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME, "J");
1149    //      jniData
1150    javaAudioTrackFields.jniData = GetFieldIDOrDie(env,
1151            audioTrackClass, JAVA_JNIDATA_FIELD_NAME, "J");
1152    //      fieldStreamType
1153    javaAudioTrackFields.fieldStreamType = GetFieldIDOrDie(env,
1154            audioTrackClass, JAVA_STREAMTYPE_FIELD_NAME, "I");
1155
1156    env->DeleteLocalRef(audioTrackClass);
1157
1158    // Get the AudioAttributes class and fields
1159    jclass audioAttrClass = FindClassOrDie(env, kAudioAttributesClassPathName);
1160    javaAudioAttrFields.fieldUsage = GetFieldIDOrDie(env, audioAttrClass, "mUsage", "I");
1161    javaAudioAttrFields.fieldContentType = GetFieldIDOrDie(env,
1162            audioAttrClass, "mContentType", "I");
1163    javaAudioAttrFields.fieldFlags = GetFieldIDOrDie(env, audioAttrClass, "mFlags", "I");
1164    javaAudioAttrFields.fieldFormattedTags = GetFieldIDOrDie(env,
1165            audioAttrClass, "mFormattedTags", "Ljava/lang/String;");
1166
1167    env->DeleteLocalRef(audioAttrClass);
1168
1169    // initialize PlaybackParams field info
1170    gPlaybackParamsFields.init(env);
1171
1172    return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
1173}
1174
1175
1176// ----------------------------------------------------------------------------
1177