android_media_AudioTrack.cpp revision 844b0475ed26a1967919a3f119448c7c3159cb25
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 <jni.h>
21#include <JNIHelp.h>
22#include <android_runtime/AndroidRuntime.h>
23
24#include <utils/Log.h>
25#include <media/AudioSystem.h>
26#include <media/AudioTrack.h>
27
28#include <binder/MemoryHeapBase.h>
29#include <binder/MemoryBase.h>
30
31#include <system/audio.h>
32
33// ----------------------------------------------------------------------------
34
35using namespace android;
36
37// ----------------------------------------------------------------------------
38static const char* const kClassPathName = "android/media/AudioTrack";
39
40struct fields_t {
41    // these fields provide access from C++ to the...
42    jmethodID postNativeEventInJava; //... event post callback method
43    jfieldID  nativeTrackInJavaObj;  // stores in Java the native AudioTrack object
44    jfieldID  jniData;      // stores in Java additional resources used by the native AudioTrack
45};
46static fields_t javaAudioTrackFields;
47
48struct audiotrack_callback_cookie {
49    jclass      audioTrack_class;
50    jobject     audioTrack_ref;
51    bool        busy;
52    Condition   cond;
53};
54
55// keep these values in sync with AudioTrack.java
56#define MODE_STATIC 0
57#define MODE_STREAM 1
58// keep these values in sync with AudioFormat.java
59#define ENCODING_PCM_16BIT 2
60#define ENCODING_PCM_8BIT  3
61
62// ----------------------------------------------------------------------------
63class AudioTrackJniStorage {
64    public:
65        sp<MemoryHeapBase>         mMemHeap;
66        sp<MemoryBase>             mMemBase;
67        audiotrack_callback_cookie mCallbackData;
68        audio_stream_type_t        mStreamType;
69
70    AudioTrackJniStorage() {
71        mCallbackData.audioTrack_class = 0;
72        mCallbackData.audioTrack_ref = 0;
73        mStreamType = AUDIO_STREAM_DEFAULT;
74    }
75
76    ~AudioTrackJniStorage() {
77        mMemBase.clear();
78        mMemHeap.clear();
79    }
80
81    bool allocSharedMem(int sizeInBytes) {
82        mMemHeap = new MemoryHeapBase(sizeInBytes, 0, "AudioTrack Heap Base");
83        if (mMemHeap->getHeapID() < 0) {
84            return false;
85        }
86        mMemBase = new MemoryBase(mMemHeap, 0, sizeInBytes);
87        return true;
88    }
89};
90
91static Mutex sLock;
92static SortedVector <audiotrack_callback_cookie *> sAudioTrackCallBackCookies;
93
94// ----------------------------------------------------------------------------
95#define DEFAULT_OUTPUT_SAMPLE_RATE   44100
96
97#define AUDIOTRACK_SUCCESS                         0
98#define AUDIOTRACK_ERROR                           -1
99#define AUDIOTRACK_ERROR_BAD_VALUE                 -2
100#define AUDIOTRACK_ERROR_INVALID_OPERATION         -3
101#define AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM         -16
102#define AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELMASK  -17
103#define AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT       -18
104#define AUDIOTRACK_ERROR_SETUP_INVALIDSTREAMTYPE   -19
105#define AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED    -20
106
107
108jint android_media_translateErrorCode(int code) {
109    switch (code) {
110    case NO_ERROR:
111        return AUDIOTRACK_SUCCESS;
112    case BAD_VALUE:
113        return AUDIOTRACK_ERROR_BAD_VALUE;
114    case INVALID_OPERATION:
115        return AUDIOTRACK_ERROR_INVALID_OPERATION;
116    default:
117        return AUDIOTRACK_ERROR;
118    }
119}
120
121
122// ----------------------------------------------------------------------------
123static void audioCallback(int event, void* user, void *info) {
124
125    audiotrack_callback_cookie *callbackInfo = (audiotrack_callback_cookie *)user;
126    {
127        Mutex::Autolock l(sLock);
128        if (sAudioTrackCallBackCookies.indexOf(callbackInfo) < 0) {
129            return;
130        }
131        callbackInfo->busy = true;
132    }
133
134    switch (event) {
135    case AudioTrack::EVENT_MARKER: {
136        JNIEnv *env = AndroidRuntime::getJNIEnv();
137        if (user && env) {
138            env->CallStaticVoidMethod(
139                callbackInfo->audioTrack_class,
140                javaAudioTrackFields.postNativeEventInJava,
141                callbackInfo->audioTrack_ref, event, 0,0, NULL);
142            if (env->ExceptionCheck()) {
143                env->ExceptionDescribe();
144                env->ExceptionClear();
145            }
146        }
147        } break;
148
149    case AudioTrack::EVENT_NEW_POS: {
150        JNIEnv *env = AndroidRuntime::getJNIEnv();
151        if (user && env) {
152            env->CallStaticVoidMethod(
153                callbackInfo->audioTrack_class,
154                javaAudioTrackFields.postNativeEventInJava,
155                callbackInfo->audioTrack_ref, event, 0,0, NULL);
156            if (env->ExceptionCheck()) {
157                env->ExceptionDescribe();
158                env->ExceptionClear();
159            }
160        }
161        } break;
162    }
163
164    {
165        Mutex::Autolock l(sLock);
166        callbackInfo->busy = false;
167        callbackInfo->cond.broadcast();
168    }
169}
170
171
172// ----------------------------------------------------------------------------
173static sp<AudioTrack> getAudioTrack(JNIEnv* env, jobject thiz)
174{
175    Mutex::Autolock l(sLock);
176    AudioTrack* const at =
177            (AudioTrack*)env->GetIntField(thiz, javaAudioTrackFields.nativeTrackInJavaObj);
178    return sp<AudioTrack>(at);
179}
180
181static sp<AudioTrack> setAudioTrack(JNIEnv* env, jobject thiz, const sp<AudioTrack>& at)
182{
183    Mutex::Autolock l(sLock);
184    sp<AudioTrack> old =
185            (AudioTrack*)env->GetIntField(thiz, javaAudioTrackFields.nativeTrackInJavaObj);
186    if (at.get()) {
187        at->incStrong((void*)setAudioTrack);
188    }
189    if (old != 0) {
190        old->decStrong((void*)setAudioTrack);
191    }
192    env->SetIntField(thiz, javaAudioTrackFields.nativeTrackInJavaObj, (int)at.get());
193    return old;
194}
195
196// ----------------------------------------------------------------------------
197static int
198android_media_AudioTrack_native_setup(JNIEnv *env, jobject thiz, jobject weak_this,
199        jint streamType, jint sampleRateInHertz, jint javaChannelMask,
200        jint audioFormat, jint buffSizeInBytes, jint memoryMode, jintArray jSession)
201{
202    ALOGV("sampleRate=%d, audioFormat(from Java)=%d, channel mask=%x, buffSize=%d",
203        sampleRateInHertz, audioFormat, javaChannelMask, buffSizeInBytes);
204    uint32_t afSampleRate;
205    size_t afFrameCount;
206
207    if (AudioSystem::getOutputFrameCount(&afFrameCount, (audio_stream_type_t) streamType) != NO_ERROR) {
208        ALOGE("Error creating AudioTrack: Could not get AudioSystem frame count.");
209        return AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM;
210    }
211    if (AudioSystem::getOutputSamplingRate(&afSampleRate, (audio_stream_type_t) streamType) != NO_ERROR) {
212        ALOGE("Error creating AudioTrack: Could not get AudioSystem sampling rate.");
213        return AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM;
214    }
215
216    // Java channel masks don't map directly to the native definition, but it's a simple shift
217    // to skip the two deprecated channel configurations "default" and "mono".
218    uint32_t nativeChannelMask = ((uint32_t)javaChannelMask) >> 2;
219
220    if (!audio_is_output_channel(nativeChannelMask)) {
221        ALOGE("Error creating AudioTrack: invalid channel mask %#x.", javaChannelMask);
222        return AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELMASK;
223    }
224
225    int nbChannels = popcount(nativeChannelMask);
226
227    // check the stream type
228    audio_stream_type_t atStreamType;
229    switch (streamType) {
230    case AUDIO_STREAM_VOICE_CALL:
231    case AUDIO_STREAM_SYSTEM:
232    case AUDIO_STREAM_RING:
233    case AUDIO_STREAM_MUSIC:
234    case AUDIO_STREAM_ALARM:
235    case AUDIO_STREAM_NOTIFICATION:
236    case AUDIO_STREAM_BLUETOOTH_SCO:
237    case AUDIO_STREAM_DTMF:
238        atStreamType = (audio_stream_type_t) streamType;
239        break;
240    default:
241        ALOGE("Error creating AudioTrack: unknown stream type.");
242        return AUDIOTRACK_ERROR_SETUP_INVALIDSTREAMTYPE;
243    }
244
245    // check the format.
246    // This function was called from Java, so we compare the format against the Java constants
247    if ((audioFormat != ENCODING_PCM_16BIT) && (audioFormat != ENCODING_PCM_8BIT)) {
248
249        ALOGE("Error creating AudioTrack: unsupported audio format.");
250        return AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT;
251    }
252
253    // for the moment 8bitPCM in MODE_STATIC is not supported natively in the AudioTrack C++ class
254    // so we declare everything as 16bitPCM, the 8->16bit conversion for MODE_STATIC will be handled
255    // in android_media_AudioTrack_native_write_byte()
256    if ((audioFormat == ENCODING_PCM_8BIT)
257        && (memoryMode == MODE_STATIC)) {
258        ALOGV("android_media_AudioTrack_native_setup(): requesting MODE_STATIC for 8bit \
259            buff size of %dbytes, switching to 16bit, buff size of %dbytes",
260            buffSizeInBytes, 2*buffSizeInBytes);
261        audioFormat = ENCODING_PCM_16BIT;
262        // we will need twice the memory to store the data
263        buffSizeInBytes *= 2;
264    }
265
266    // compute the frame count
267    int bytesPerSample = audioFormat == ENCODING_PCM_16BIT ? 2 : 1;
268    audio_format_t format = audioFormat == ENCODING_PCM_16BIT ?
269            AUDIO_FORMAT_PCM_16_BIT : AUDIO_FORMAT_PCM_8_BIT;
270    int frameCount = buffSizeInBytes / (nbChannels * bytesPerSample);
271
272    jclass clazz = env->GetObjectClass(thiz);
273    if (clazz == NULL) {
274        ALOGE("Can't find %s when setting up callback.", kClassPathName);
275        return AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED;
276    }
277
278    if (jSession == NULL) {
279        ALOGE("Error creating AudioTrack: invalid session ID pointer");
280        return AUDIOTRACK_ERROR;
281    }
282
283    jint* nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL);
284    if (nSession == NULL) {
285        ALOGE("Error creating AudioTrack: Error retrieving session id pointer");
286        return AUDIOTRACK_ERROR;
287    }
288    int sessionId = nSession[0];
289    env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
290    nSession = NULL;
291
292    // create the native AudioTrack object
293    sp<AudioTrack> lpTrack = new AudioTrack();
294
295    // initialize the callback information:
296    // this data will be passed with every AudioTrack callback
297    AudioTrackJniStorage* lpJniStorage = new AudioTrackJniStorage();
298    lpJniStorage->mStreamType = atStreamType;
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    switch (memoryMode) {
306    case MODE_STREAM:
307
308        lpTrack->set(
309            atStreamType,// stream type
310            sampleRateInHertz,
311            format,// word length, PCM
312            nativeChannelMask,
313            frameCount,
314            AUDIO_OUTPUT_FLAG_NONE,
315            audioCallback, &(lpJniStorage->mCallbackData),//callback, callback data (user)
316            0,// notificationFrames == 0 since not using EVENT_MORE_DATA to feed the AudioTrack
317            0,// shared mem
318            true,// thread can call Java
319            sessionId);// audio session ID
320        break;
321
322    case MODE_STATIC:
323        // AudioTrack is using shared memory
324
325        if (!lpJniStorage->allocSharedMem(buffSizeInBytes)) {
326            ALOGE("Error creating AudioTrack in static mode: error creating mem heap base");
327            goto native_init_failure;
328        }
329
330        lpTrack->set(
331            atStreamType,// stream type
332            sampleRateInHertz,
333            format,// word length, PCM
334            nativeChannelMask,
335            frameCount,
336            AUDIO_OUTPUT_FLAG_NONE,
337            audioCallback, &(lpJniStorage->mCallbackData),//callback, callback data (user));
338            0,// notificationFrames == 0 since not using EVENT_MORE_DATA to feed the AudioTrack
339            lpJniStorage->mMemBase,// shared mem
340            true,// thread can call Java
341            sessionId);// audio session ID
342        break;
343
344    default:
345        ALOGE("Unknown mode %d", memoryMode);
346        goto native_init_failure;
347    }
348
349    if (lpTrack->initCheck() != NO_ERROR) {
350        ALOGE("Error initializing AudioTrack");
351        goto native_init_failure;
352    }
353
354    nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL);
355    if (nSession == NULL) {
356        ALOGE("Error creating AudioTrack: Error retrieving session id pointer");
357        goto native_init_failure;
358    }
359    // read the audio session ID back from AudioTrack in case we create a new session
360    nSession[0] = lpTrack->getSessionId();
361    env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
362    nSession = NULL;
363
364    {   // scope for the lock
365        Mutex::Autolock l(sLock);
366        sAudioTrackCallBackCookies.add(&lpJniStorage->mCallbackData);
367    }
368    // save our newly created C++ AudioTrack in the "nativeTrackInJavaObj" field
369    // of the Java object (in mNativeTrackInJavaObj)
370    setAudioTrack(env, thiz, lpTrack);
371
372    // save the JNI resources so we can free them later
373    //ALOGV("storing lpJniStorage: %x\n", (int)lpJniStorage);
374    env->SetIntField(thiz, javaAudioTrackFields.jniData, (int)lpJniStorage);
375
376    return AUDIOTRACK_SUCCESS;
377
378    // failures:
379native_init_failure:
380    if (nSession != NULL) {
381        env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
382    }
383    env->DeleteGlobalRef(lpJniStorage->mCallbackData.audioTrack_class);
384    env->DeleteGlobalRef(lpJniStorage->mCallbackData.audioTrack_ref);
385    delete lpJniStorage;
386    env->SetIntField(thiz, javaAudioTrackFields.jniData, 0);
387
388    return AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED;
389}
390
391
392// ----------------------------------------------------------------------------
393static void
394android_media_AudioTrack_start(JNIEnv *env, jobject thiz)
395{
396    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
397    if (lpTrack == NULL) {
398        jniThrowException(env, "java/lang/IllegalStateException",
399            "Unable to retrieve AudioTrack pointer for start()");
400        return;
401    }
402
403    lpTrack->start();
404}
405
406
407// ----------------------------------------------------------------------------
408static void
409android_media_AudioTrack_stop(JNIEnv *env, jobject thiz)
410{
411    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
412    if (lpTrack == NULL) {
413        jniThrowException(env, "java/lang/IllegalStateException",
414            "Unable to retrieve AudioTrack pointer for stop()");
415        return;
416    }
417
418    lpTrack->stop();
419}
420
421
422// ----------------------------------------------------------------------------
423static void
424android_media_AudioTrack_pause(JNIEnv *env, jobject thiz)
425{
426    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
427    if (lpTrack == NULL) {
428        jniThrowException(env, "java/lang/IllegalStateException",
429            "Unable to retrieve AudioTrack pointer for pause()");
430        return;
431    }
432
433    lpTrack->pause();
434}
435
436
437// ----------------------------------------------------------------------------
438static void
439android_media_AudioTrack_flush(JNIEnv *env, jobject thiz)
440{
441    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
442    if (lpTrack == NULL) {
443        jniThrowException(env, "java/lang/IllegalStateException",
444            "Unable to retrieve AudioTrack pointer for flush()");
445        return;
446    }
447
448    lpTrack->flush();
449}
450
451// ----------------------------------------------------------------------------
452static void
453android_media_AudioTrack_set_volume(JNIEnv *env, jobject thiz, jfloat leftVol, jfloat rightVol )
454{
455    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
456    if (lpTrack == NULL) {
457        jniThrowException(env, "java/lang/IllegalStateException",
458            "Unable to retrieve AudioTrack pointer for setVolume()");
459        return;
460    }
461
462    lpTrack->setVolume(leftVol, rightVol);
463}
464
465// ----------------------------------------------------------------------------
466
467#define CALLBACK_COND_WAIT_TIMEOUT_MS 1000
468static void android_media_AudioTrack_native_release(JNIEnv *env,  jobject thiz) {
469    sp<AudioTrack> lpTrack = setAudioTrack(env, thiz, 0);
470    if (lpTrack == NULL) {
471        return;
472    }
473    //ALOGV("deleting lpTrack: %x\n", (int)lpTrack);
474    lpTrack->stop();
475
476    // delete the JNI data
477    AudioTrackJniStorage* pJniStorage = (AudioTrackJniStorage *)env->GetIntField(
478        thiz, javaAudioTrackFields.jniData);
479    // reset the native resources in the Java object so any attempt to access
480    // them after a call to release fails.
481    env->SetIntField(thiz, javaAudioTrackFields.jniData, 0);
482
483    if (pJniStorage) {
484        Mutex::Autolock l(sLock);
485        audiotrack_callback_cookie *lpCookie = &pJniStorage->mCallbackData;
486        //ALOGV("deleting pJniStorage: %x\n", (int)pJniStorage);
487        while (lpCookie->busy) {
488            if (lpCookie->cond.waitRelative(sLock,
489                                            milliseconds(CALLBACK_COND_WAIT_TIMEOUT_MS)) !=
490                                                    NO_ERROR) {
491                break;
492            }
493        }
494        sAudioTrackCallBackCookies.remove(lpCookie);
495        // delete global refs created in native_setup
496        env->DeleteGlobalRef(lpCookie->audioTrack_class);
497        env->DeleteGlobalRef(lpCookie->audioTrack_ref);
498        delete pJniStorage;
499    }
500}
501
502
503// ----------------------------------------------------------------------------
504static void android_media_AudioTrack_native_finalize(JNIEnv *env,  jobject thiz) {
505    //ALOGV("android_media_AudioTrack_native_finalize jobject: %x\n", (int)thiz);
506    android_media_AudioTrack_native_release(env, thiz);
507}
508
509// ----------------------------------------------------------------------------
510jint writeToTrack(const sp<AudioTrack>& track, jint audioFormat, jbyte* data,
511                  jint offsetInBytes, jint sizeInBytes) {
512    // give the data to the native AudioTrack object (the data starts at the offset)
513    ssize_t written = 0;
514    // regular write() or copy the data to the AudioTrack's shared memory?
515    if (track->sharedBuffer() == 0) {
516        written = track->write(data + offsetInBytes, sizeInBytes);
517        // for compatibility with earlier behavior of write(), return 0 in this case
518        if (written == (ssize_t) WOULD_BLOCK) {
519            written = 0;
520        }
521    } else {
522        if (audioFormat == ENCODING_PCM_16BIT) {
523            // writing to shared memory, check for capacity
524            if ((size_t)sizeInBytes > track->sharedBuffer()->size()) {
525                sizeInBytes = track->sharedBuffer()->size();
526            }
527            memcpy(track->sharedBuffer()->pointer(), data + offsetInBytes, sizeInBytes);
528            written = sizeInBytes;
529        } else if (audioFormat == ENCODING_PCM_8BIT) {
530            // data contains 8bit data we need to expand to 16bit before copying
531            // to the shared memory
532            // writing to shared memory, check for capacity,
533            // note that input data will occupy 2X the input space due to 8 to 16bit conversion
534            if (((size_t)sizeInBytes)*2 > track->sharedBuffer()->size()) {
535                sizeInBytes = track->sharedBuffer()->size() / 2;
536            }
537            int count = sizeInBytes;
538            int16_t *dst = (int16_t *)track->sharedBuffer()->pointer();
539            const int8_t *src = (const int8_t *)(data + offsetInBytes);
540            while (count--) {
541                *dst++ = (int16_t)(*src++^0x80) << 8;
542            }
543            // even though we wrote 2*sizeInBytes, we only report sizeInBytes as written to hide
544            // the 8bit mixer restriction from the user of this function
545            written = sizeInBytes;
546        }
547    }
548    return written;
549
550}
551
552// ----------------------------------------------------------------------------
553static jint android_media_AudioTrack_native_write_byte(JNIEnv *env,  jobject thiz,
554                                                  jbyteArray javaAudioData,
555                                                  jint offsetInBytes, jint sizeInBytes,
556                                                  jint javaAudioFormat) {
557    //ALOGV("android_media_AudioTrack_native_write_byte(offset=%d, sizeInBytes=%d) called",
558    //    offsetInBytes, sizeInBytes);
559    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
560    if (lpTrack == NULL) {
561        jniThrowException(env, "java/lang/IllegalStateException",
562            "Unable to retrieve AudioTrack pointer for write()");
563        return 0;
564    }
565
566    // get the pointer for the audio data from the java array
567    // NOTE: We may use GetPrimitiveArrayCritical() when the JNI implementation changes in such
568    // a way that it becomes much more efficient. When doing so, we will have to prevent the
569    // AudioSystem callback to be called while in critical section (in case of media server
570    // process crash for instance)
571    jbyte* cAudioData = NULL;
572    if (javaAudioData) {
573        cAudioData = (jbyte *)env->GetByteArrayElements(javaAudioData, NULL);
574        if (cAudioData == NULL) {
575            ALOGE("Error retrieving source of audio data to play, can't play");
576            return 0; // out of memory or no data to load
577        }
578    } else {
579        ALOGE("NULL java array of audio data to play, can't play");
580        return 0;
581    }
582
583    jint written = writeToTrack(lpTrack, javaAudioFormat, cAudioData, offsetInBytes, sizeInBytes);
584
585    env->ReleaseByteArrayElements(javaAudioData, cAudioData, 0);
586
587    //ALOGV("write wrote %d (tried %d) bytes in the native AudioTrack with offset %d",
588    //     (int)written, (int)(sizeInBytes), (int)offsetInBytes);
589    return written;
590}
591
592
593// ----------------------------------------------------------------------------
594static jint android_media_AudioTrack_native_write_short(JNIEnv *env,  jobject thiz,
595                                                  jshortArray javaAudioData,
596                                                  jint offsetInShorts, jint sizeInShorts,
597                                                  jint javaAudioFormat) {
598    jint written = android_media_AudioTrack_native_write_byte(env, thiz,
599                                                 (jbyteArray) javaAudioData,
600                                                 offsetInShorts*2, sizeInShorts*2,
601                                                 javaAudioFormat);
602    if (written > 0) {
603        written /= 2;
604    }
605    return written;
606}
607
608
609// ----------------------------------------------------------------------------
610static jint android_media_AudioTrack_get_native_frame_count(JNIEnv *env,  jobject thiz) {
611    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
612    if (lpTrack == NULL) {
613        jniThrowException(env, "java/lang/IllegalStateException",
614            "Unable to retrieve AudioTrack pointer for frameCount()");
615        return AUDIOTRACK_ERROR;
616    }
617
618    return lpTrack->frameCount();
619}
620
621
622// ----------------------------------------------------------------------------
623static jint android_media_AudioTrack_set_playback_rate(JNIEnv *env,  jobject thiz,
624        jint sampleRateInHz) {
625    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
626    if (lpTrack == NULL) {
627        jniThrowException(env, "java/lang/IllegalStateException",
628            "Unable to retrieve AudioTrack pointer for setSampleRate()");
629        return AUDIOTRACK_ERROR;
630    }
631    return android_media_translateErrorCode(lpTrack->setSampleRate(sampleRateInHz));
632}
633
634
635// ----------------------------------------------------------------------------
636static jint android_media_AudioTrack_get_playback_rate(JNIEnv *env,  jobject thiz) {
637    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
638    if (lpTrack == NULL) {
639        jniThrowException(env, "java/lang/IllegalStateException",
640            "Unable to retrieve AudioTrack pointer for getSampleRate()");
641        return AUDIOTRACK_ERROR;
642    }
643    return (jint) lpTrack->getSampleRate();
644}
645
646
647// ----------------------------------------------------------------------------
648static jint android_media_AudioTrack_set_marker_pos(JNIEnv *env,  jobject thiz,
649        jint markerPos) {
650    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
651    if (lpTrack == NULL) {
652        jniThrowException(env, "java/lang/IllegalStateException",
653            "Unable to retrieve AudioTrack pointer for setMarkerPosition()");
654        return AUDIOTRACK_ERROR;
655    }
656    return android_media_translateErrorCode( lpTrack->setMarkerPosition(markerPos) );
657}
658
659
660// ----------------------------------------------------------------------------
661static jint android_media_AudioTrack_get_marker_pos(JNIEnv *env,  jobject thiz) {
662    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
663    uint32_t markerPos = 0;
664
665    if (lpTrack == NULL) {
666        jniThrowException(env, "java/lang/IllegalStateException",
667            "Unable to retrieve AudioTrack pointer for getMarkerPosition()");
668        return AUDIOTRACK_ERROR;
669    }
670    lpTrack->getMarkerPosition(&markerPos);
671    return (jint)markerPos;
672}
673
674
675// ----------------------------------------------------------------------------
676static jint android_media_AudioTrack_set_pos_update_period(JNIEnv *env,  jobject thiz,
677        jint period) {
678    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
679    if (lpTrack == NULL) {
680        jniThrowException(env, "java/lang/IllegalStateException",
681            "Unable to retrieve AudioTrack pointer for setPositionUpdatePeriod()");
682        return AUDIOTRACK_ERROR;
683    }
684    return android_media_translateErrorCode( lpTrack->setPositionUpdatePeriod(period) );
685}
686
687
688// ----------------------------------------------------------------------------
689static jint android_media_AudioTrack_get_pos_update_period(JNIEnv *env,  jobject thiz) {
690    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
691    uint32_t period = 0;
692
693    if (lpTrack == NULL) {
694        jniThrowException(env, "java/lang/IllegalStateException",
695            "Unable to retrieve AudioTrack pointer for getPositionUpdatePeriod()");
696        return AUDIOTRACK_ERROR;
697    }
698    lpTrack->getPositionUpdatePeriod(&period);
699    return (jint)period;
700}
701
702
703// ----------------------------------------------------------------------------
704static jint android_media_AudioTrack_set_position(JNIEnv *env,  jobject thiz,
705        jint position) {
706    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
707    if (lpTrack == NULL) {
708        jniThrowException(env, "java/lang/IllegalStateException",
709            "Unable to retrieve AudioTrack pointer for setPosition()");
710        return AUDIOTRACK_ERROR;
711    }
712    return android_media_translateErrorCode( lpTrack->setPosition(position) );
713}
714
715
716// ----------------------------------------------------------------------------
717static jint android_media_AudioTrack_get_position(JNIEnv *env,  jobject thiz) {
718    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
719    uint32_t position = 0;
720
721    if (lpTrack == NULL) {
722        jniThrowException(env, "java/lang/IllegalStateException",
723            "Unable to retrieve AudioTrack pointer for getPosition()");
724        return AUDIOTRACK_ERROR;
725    }
726    lpTrack->getPosition(&position);
727    return (jint)position;
728}
729
730
731// ----------------------------------------------------------------------------
732static jint android_media_AudioTrack_get_latency(JNIEnv *env,  jobject thiz) {
733    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
734
735    if (lpTrack == NULL) {
736        jniThrowException(env, "java/lang/IllegalStateException",
737            "Unable to retrieve AudioTrack pointer for latency()");
738        return AUDIOTRACK_ERROR;
739    }
740    return (jint)lpTrack->latency();
741}
742
743
744// ----------------------------------------------------------------------------
745static jint android_media_AudioTrack_set_loop(JNIEnv *env,  jobject thiz,
746        jint loopStart, jint loopEnd, jint loopCount) {
747    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
748    if (lpTrack == NULL) {
749        jniThrowException(env, "java/lang/IllegalStateException",
750            "Unable to retrieve AudioTrack pointer for setLoop()");
751        return AUDIOTRACK_ERROR;
752    }
753    return android_media_translateErrorCode( lpTrack->setLoop(loopStart, loopEnd, loopCount) );
754}
755
756
757// ----------------------------------------------------------------------------
758static jint android_media_AudioTrack_reload(JNIEnv *env,  jobject thiz) {
759    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
760    if (lpTrack == NULL) {
761        jniThrowException(env, "java/lang/IllegalStateException",
762            "Unable to retrieve AudioTrack pointer for reload()");
763        return AUDIOTRACK_ERROR;
764    }
765    return android_media_translateErrorCode( lpTrack->reload() );
766}
767
768
769// ----------------------------------------------------------------------------
770static jint android_media_AudioTrack_get_output_sample_rate(JNIEnv *env,  jobject thiz,
771        jint javaStreamType) {
772    uint32_t afSamplingRate;
773    // convert the stream type from Java to native value
774    // FIXME: code duplication with android_media_AudioTrack_native_setup()
775    audio_stream_type_t nativeStreamType;
776    switch (javaStreamType) {
777    case AUDIO_STREAM_VOICE_CALL:
778    case AUDIO_STREAM_SYSTEM:
779    case AUDIO_STREAM_RING:
780    case AUDIO_STREAM_MUSIC:
781    case AUDIO_STREAM_ALARM:
782    case AUDIO_STREAM_NOTIFICATION:
783    case AUDIO_STREAM_BLUETOOTH_SCO:
784    case AUDIO_STREAM_DTMF:
785        nativeStreamType = (audio_stream_type_t) javaStreamType;
786        break;
787    default:
788        nativeStreamType = AUDIO_STREAM_DEFAULT;
789        break;
790    }
791
792    if (AudioSystem::getOutputSamplingRate(&afSamplingRate, nativeStreamType) != NO_ERROR) {
793        ALOGE("AudioSystem::getOutputSamplingRate() for stream type %d failed in AudioTrack JNI",
794            nativeStreamType);
795        return DEFAULT_OUTPUT_SAMPLE_RATE;
796    } else {
797        return afSamplingRate;
798    }
799}
800
801
802// ----------------------------------------------------------------------------
803// returns the minimum required size for the successful creation of a streaming AudioTrack
804// returns -1 if there was an error querying the hardware.
805static jint android_media_AudioTrack_get_min_buff_size(JNIEnv *env,  jobject thiz,
806    jint sampleRateInHertz, jint nbChannels, jint audioFormat) {
807
808    size_t frameCount = 0;
809    if (AudioTrack::getMinFrameCount(&frameCount, AUDIO_STREAM_DEFAULT,
810            sampleRateInHertz) != NO_ERROR) {
811        return -1;
812    }
813    return frameCount * nbChannels * (audioFormat == ENCODING_PCM_16BIT ? 2 : 1);
814}
815
816// ----------------------------------------------------------------------------
817static void
818android_media_AudioTrack_setAuxEffectSendLevel(JNIEnv *env, jobject thiz, jfloat level )
819{
820    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
821    if (lpTrack == NULL ) {
822        jniThrowException(env, "java/lang/IllegalStateException",
823            "Unable to retrieve AudioTrack pointer for setAuxEffectSendLevel()");
824        return;
825    }
826
827    lpTrack->setAuxEffectSendLevel(level);
828}
829
830// ----------------------------------------------------------------------------
831static jint android_media_AudioTrack_attachAuxEffect(JNIEnv *env,  jobject thiz,
832        jint effectId) {
833    sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
834    if (lpTrack == NULL) {
835        jniThrowException(env, "java/lang/IllegalStateException",
836            "Unable to retrieve AudioTrack pointer for attachAuxEffect()");
837        return AUDIOTRACK_ERROR;
838    }
839    return android_media_translateErrorCode( lpTrack->attachAuxEffect(effectId) );
840}
841
842// ----------------------------------------------------------------------------
843// ----------------------------------------------------------------------------
844static JNINativeMethod gMethods[] = {
845    // name,              signature,     funcPtr
846    {"native_start",         "()V",      (void *)android_media_AudioTrack_start},
847    {"native_stop",          "()V",      (void *)android_media_AudioTrack_stop},
848    {"native_pause",         "()V",      (void *)android_media_AudioTrack_pause},
849    {"native_flush",         "()V",      (void *)android_media_AudioTrack_flush},
850    {"native_setup",         "(Ljava/lang/Object;IIIIII[I)I",
851                                         (void *)android_media_AudioTrack_native_setup},
852    {"native_finalize",      "()V",      (void *)android_media_AudioTrack_native_finalize},
853    {"native_release",       "()V",      (void *)android_media_AudioTrack_native_release},
854    {"native_write_byte",    "([BIII)I", (void *)android_media_AudioTrack_native_write_byte},
855    {"native_write_short",   "([SIII)I", (void *)android_media_AudioTrack_native_write_short},
856    {"native_setVolume",     "(FF)V",    (void *)android_media_AudioTrack_set_volume},
857    {"native_get_native_frame_count",
858                             "()I",      (void *)android_media_AudioTrack_get_native_frame_count},
859    {"native_set_playback_rate",
860                             "(I)I",     (void *)android_media_AudioTrack_set_playback_rate},
861    {"native_get_playback_rate",
862                             "()I",      (void *)android_media_AudioTrack_get_playback_rate},
863    {"native_set_marker_pos","(I)I",     (void *)android_media_AudioTrack_set_marker_pos},
864    {"native_get_marker_pos","()I",      (void *)android_media_AudioTrack_get_marker_pos},
865    {"native_set_pos_update_period",
866                             "(I)I",     (void *)android_media_AudioTrack_set_pos_update_period},
867    {"native_get_pos_update_period",
868                             "()I",      (void *)android_media_AudioTrack_get_pos_update_period},
869    {"native_set_position",  "(I)I",     (void *)android_media_AudioTrack_set_position},
870    {"native_get_position",  "()I",      (void *)android_media_AudioTrack_get_position},
871    {"native_get_latency",   "()I",      (void *)android_media_AudioTrack_get_latency},
872    {"native_set_loop",      "(III)I",   (void *)android_media_AudioTrack_set_loop},
873    {"native_reload_static", "()I",      (void *)android_media_AudioTrack_reload},
874    {"native_get_output_sample_rate",
875                             "(I)I",      (void *)android_media_AudioTrack_get_output_sample_rate},
876    {"native_get_min_buff_size",
877                             "(III)I",   (void *)android_media_AudioTrack_get_min_buff_size},
878    {"native_setAuxEffectSendLevel",
879                             "(F)V",     (void *)android_media_AudioTrack_setAuxEffectSendLevel},
880    {"native_attachAuxEffect",
881                             "(I)I",     (void *)android_media_AudioTrack_attachAuxEffect},
882};
883
884
885// field names found in android/media/AudioTrack.java
886#define JAVA_POSTEVENT_CALLBACK_NAME                    "postEventFromNative"
887#define JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME            "mNativeTrackInJavaObj"
888#define JAVA_JNIDATA_FIELD_NAME                         "mJniData"
889
890// ----------------------------------------------------------------------------
891// preconditions:
892//    theClass is valid
893bool android_media_getIntConstantFromClass(JNIEnv* pEnv, jclass theClass, const char* className,
894                             const char* constName, int* constVal) {
895    jfieldID javaConst = NULL;
896    javaConst = pEnv->GetStaticFieldID(theClass, constName, "I");
897    if (javaConst != NULL) {
898        *constVal = pEnv->GetStaticIntField(theClass, javaConst);
899        return true;
900    } else {
901        ALOGE("Can't find %s.%s", className, constName);
902        return false;
903    }
904}
905
906
907// ----------------------------------------------------------------------------
908int register_android_media_AudioTrack(JNIEnv *env)
909{
910    javaAudioTrackFields.nativeTrackInJavaObj = NULL;
911    javaAudioTrackFields.postNativeEventInJava = NULL;
912
913    // Get the AudioTrack class
914    jclass audioTrackClass = env->FindClass(kClassPathName);
915    if (audioTrackClass == NULL) {
916        ALOGE("Can't find %s", kClassPathName);
917        return -1;
918    }
919
920    // Get the postEvent method
921    javaAudioTrackFields.postNativeEventInJava = env->GetStaticMethodID(
922            audioTrackClass,
923            JAVA_POSTEVENT_CALLBACK_NAME, "(Ljava/lang/Object;IIILjava/lang/Object;)V");
924    if (javaAudioTrackFields.postNativeEventInJava == NULL) {
925        ALOGE("Can't find AudioTrack.%s", JAVA_POSTEVENT_CALLBACK_NAME);
926        return -1;
927    }
928
929    // Get the variables fields
930    //      nativeTrackInJavaObj
931    javaAudioTrackFields.nativeTrackInJavaObj = env->GetFieldID(
932            audioTrackClass,
933            JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME, "I");
934    if (javaAudioTrackFields.nativeTrackInJavaObj == NULL) {
935        ALOGE("Can't find AudioTrack.%s", JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME);
936        return -1;
937    }
938    //      jniData;
939    javaAudioTrackFields.jniData = env->GetFieldID(
940            audioTrackClass,
941            JAVA_JNIDATA_FIELD_NAME, "I");
942    if (javaAudioTrackFields.jniData == NULL) {
943        ALOGE("Can't find AudioTrack.%s", JAVA_JNIDATA_FIELD_NAME);
944        return -1;
945    }
946
947    return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods));
948}
949
950
951// ----------------------------------------------------------------------------
952