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