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