android_media_AudioTrack.cpp revision 0795272aa226f4e965968a03daddc53ce30b7cda
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       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// ----------------------------------------------------------------------------
436jint writeToTrack(AudioTrack* pTrack, jint audioFormat, jbyte* data,
437                  jint offsetInBytes, jint sizeInBytes) {
438    // give the data to the native AudioTrack object (the data starts at the offset)
439    ssize_t written = 0;
440    // regular write() or copy the data to the AudioTrack's shared memory?
441    if (pTrack->sharedBuffer() == 0) {
442        written = pTrack->write(data + offsetInBytes, sizeInBytes);
443    } else {
444        if (audioFormat == javaAudioTrackFields.PCM16) {
445            // writing to shared memory, check for capacity
446            if ((size_t)sizeInBytes > pTrack->sharedBuffer()->size()) {
447                sizeInBytes = pTrack->sharedBuffer()->size();
448            }
449            memcpy(pTrack->sharedBuffer()->pointer(), data + offsetInBytes, sizeInBytes);
450            written = sizeInBytes;
451        } else if (audioFormat == javaAudioTrackFields.PCM8) {
452            // data contains 8bit data we need to expand to 16bit before copying
453            // to the shared memory
454            // writing to shared memory, check for capacity,
455            // note that input data will occupy 2X the input space due to 8 to 16bit conversion
456            if (((size_t)sizeInBytes)*2 > pTrack->sharedBuffer()->size()) {
457                sizeInBytes = pTrack->sharedBuffer()->size() / 2;
458            }
459            int count = sizeInBytes;
460            int16_t *dst = (int16_t *)pTrack->sharedBuffer()->pointer();
461            const int8_t *src = (const int8_t *)(data + offsetInBytes);
462            while(count--) {
463                *dst++ = (int16_t)(*src++^0x80) << 8;
464            }
465            // even though we wrote 2*sizeInBytes, we only report sizeInBytes as written to hide
466            // the 8bit mixer restriction from the user of this function
467            written = sizeInBytes;
468        }
469    }
470    return written;
471
472}
473
474// ----------------------------------------------------------------------------
475static jint android_media_AudioTrack_native_write(JNIEnv *env,  jobject thiz,
476                                                  jbyteArray javaAudioData,
477                                                  jint offsetInBytes, jint sizeInBytes,
478                                                  jint javaAudioFormat) {
479    jbyte* cAudioData = NULL;
480    AudioTrack *lpTrack = NULL;
481    //LOGV("android_media_AudioTrack_native_write(offset=%d, sizeInBytes=%d) called",
482    //    offsetInBytes, sizeInBytes);
483
484    // get the audio track to load with samples
485    lpTrack = (AudioTrack *)env->GetIntField(thiz, javaAudioTrackFields.nativeTrackInJavaObj);
486    if (lpTrack == NULL) {
487        jniThrowException(env, "java/lang/IllegalStateException",
488            "Unable to retrieve AudioTrack pointer for write()");
489    }
490
491    // get the pointer for the audio data from the java array
492    if (javaAudioData) {
493        cAudioData = (jbyte *)env->GetPrimitiveArrayCritical(javaAudioData, NULL);
494        if (cAudioData == NULL) {
495            LOGE("Error retrieving source of audio data to play, can't play");
496            return 0; // out of memory or no data to load
497        }
498    } else {
499        LOGE("NULL java array of audio data to play, can't play");
500        return 0;
501    }
502
503    jint written = writeToTrack(lpTrack, javaAudioFormat, cAudioData, offsetInBytes, sizeInBytes);
504
505    env->ReleasePrimitiveArrayCritical(javaAudioData, cAudioData, 0);
506
507    //LOGV("write wrote %d (tried %d) bytes in the native AudioTrack with offset %d",
508    //     (int)written, (int)(sizeInBytes), (int)offsetInBytes);
509    return written;
510}
511
512
513// ----------------------------------------------------------------------------
514static jint android_media_AudioTrack_native_write_short(JNIEnv *env,  jobject thiz,
515                                                  jshortArray javaAudioData,
516                                                  jint offsetInShorts, jint sizeInShorts,
517                                                  jint javaAudioFormat) {
518    return (android_media_AudioTrack_native_write(env, thiz,
519                                                 (jbyteArray) javaAudioData,
520                                                 offsetInShorts*2, sizeInShorts*2,
521                                                 javaAudioFormat)
522            / 2);
523}
524
525
526// ----------------------------------------------------------------------------
527static jint android_media_AudioTrack_get_native_frame_count(JNIEnv *env,  jobject thiz) {
528    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
529        thiz, javaAudioTrackFields.nativeTrackInJavaObj);
530
531    if (lpTrack) {
532        return lpTrack->frameCount();
533    } else {
534        jniThrowException(env, "java/lang/IllegalStateException",
535            "Unable to retrieve AudioTrack pointer for frameCount()");
536        return AUDIOTRACK_ERROR;
537    }
538}
539
540
541// ----------------------------------------------------------------------------
542static void android_media_AudioTrack_set_playback_rate(JNIEnv *env,  jobject thiz,
543        jint sampleRateInHz) {
544    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
545                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
546
547    if (lpTrack) {
548        lpTrack->setSampleRate(sampleRateInHz);
549    } else {
550        jniThrowException(env, "java/lang/IllegalStateException",
551            "Unable to retrieve AudioTrack pointer for setSampleRate()");
552    }
553}
554
555
556// ----------------------------------------------------------------------------
557static jint android_media_AudioTrack_get_playback_rate(JNIEnv *env,  jobject thiz) {
558    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
559                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
560
561    if (lpTrack) {
562        return (jint) lpTrack->getSampleRate();
563    } else {
564        jniThrowException(env, "java/lang/IllegalStateException",
565            "Unable to retrieve AudioTrack pointer for getSampleRate()");
566        return AUDIOTRACK_ERROR;
567    }
568}
569
570
571// ----------------------------------------------------------------------------
572static jint android_media_AudioTrack_set_marker_pos(JNIEnv *env,  jobject thiz,
573        jint markerPos) {
574
575    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
576                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
577
578    if (lpTrack) {
579        return android_media_translateErrorCode( lpTrack->setMarkerPosition(markerPos) );
580    } else {
581        jniThrowException(env, "java/lang/IllegalStateException",
582            "Unable to retrieve AudioTrack pointer for setMarkerPosition()");
583        return AUDIOTRACK_ERROR;
584    }
585}
586
587
588// ----------------------------------------------------------------------------
589static jint android_media_AudioTrack_get_marker_pos(JNIEnv *env,  jobject thiz) {
590
591    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
592                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
593    uint32_t markerPos = 0;
594
595    if (lpTrack) {
596        lpTrack->getMarkerPosition(&markerPos);
597        return (jint)markerPos;
598    } else {
599        jniThrowException(env, "java/lang/IllegalStateException",
600            "Unable to retrieve AudioTrack pointer for getMarkerPosition()");
601        return AUDIOTRACK_ERROR;
602    }
603}
604
605
606// ----------------------------------------------------------------------------
607static jint android_media_AudioTrack_set_pos_update_period(JNIEnv *env,  jobject thiz,
608        jint period) {
609
610    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
611                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
612
613    if (lpTrack) {
614        return android_media_translateErrorCode( lpTrack->setPositionUpdatePeriod(period) );
615    } else {
616        jniThrowException(env, "java/lang/IllegalStateException",
617            "Unable to retrieve AudioTrack pointer for setPositionUpdatePeriod()");
618        return AUDIOTRACK_ERROR;
619    }
620}
621
622
623// ----------------------------------------------------------------------------
624static jint android_media_AudioTrack_get_pos_update_period(JNIEnv *env,  jobject thiz) {
625
626    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
627                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
628    uint32_t period = 0;
629
630    if (lpTrack) {
631        lpTrack->getPositionUpdatePeriod(&period);
632        return (jint)period;
633    } else {
634        jniThrowException(env, "java/lang/IllegalStateException",
635            "Unable to retrieve AudioTrack pointer for getPositionUpdatePeriod()");
636        return AUDIOTRACK_ERROR;
637    }
638}
639
640
641// ----------------------------------------------------------------------------
642static jint android_media_AudioTrack_set_position(JNIEnv *env,  jobject thiz,
643        jint position) {
644
645    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
646                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
647
648    if (lpTrack) {
649        return android_media_translateErrorCode( lpTrack->setPosition(position) );
650    } else {
651        jniThrowException(env, "java/lang/IllegalStateException",
652            "Unable to retrieve AudioTrack pointer for setPosition()");
653        return AUDIOTRACK_ERROR;
654    }
655}
656
657
658// ----------------------------------------------------------------------------
659static jint android_media_AudioTrack_get_position(JNIEnv *env,  jobject thiz) {
660
661    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
662                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
663    uint32_t position = 0;
664
665    if (lpTrack) {
666        lpTrack->getPosition(&position);
667        return (jint)position;
668    }  else {
669        jniThrowException(env, "java/lang/IllegalStateException",
670            "Unable to retrieve AudioTrack pointer for getPosition()");
671        return AUDIOTRACK_ERROR;
672    }
673}
674
675
676// ----------------------------------------------------------------------------
677static jint android_media_AudioTrack_set_loop(JNIEnv *env,  jobject thiz,
678        jint loopStart, jint loopEnd, jint loopCount) {
679
680     AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
681                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
682     if (lpTrack) {
683        return android_media_translateErrorCode( lpTrack->setLoop(loopStart, loopEnd, loopCount) );
684     }  else {
685        jniThrowException(env, "java/lang/IllegalStateException",
686            "Unable to retrieve AudioTrack pointer for setLoop()");
687        return AUDIOTRACK_ERROR;
688    }
689}
690
691
692// ----------------------------------------------------------------------------
693static jint android_media_AudioTrack_reload(JNIEnv *env,  jobject thiz) {
694
695     AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
696                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
697     if (lpTrack) {
698        return android_media_translateErrorCode( lpTrack->reload() );
699     } else {
700        jniThrowException(env, "java/lang/IllegalStateException",
701            "Unable to retrieve AudioTrack pointer for reload()");
702        return AUDIOTRACK_ERROR;
703    }
704}
705
706
707// ----------------------------------------------------------------------------
708static jint android_media_AudioTrack_get_output_sample_rate(JNIEnv *env,  jobject thiz,
709        jint javaStreamType) {
710    int afSamplingRate;
711    // convert the stream type from Java to native value
712    // FIXME: code duplication with android_media_AudioTrack_native_setup()
713    AudioSystem::stream_type nativeStreamType;
714    if (javaStreamType == javaAudioTrackFields.STREAM_VOICE_CALL) {
715        nativeStreamType = AudioSystem::VOICE_CALL;
716    } else if (javaStreamType == javaAudioTrackFields.STREAM_SYSTEM) {
717        nativeStreamType = AudioSystem::SYSTEM;
718    } else if (javaStreamType == javaAudioTrackFields.STREAM_RING) {
719        nativeStreamType = AudioSystem::RING;
720    } else if (javaStreamType == javaAudioTrackFields.STREAM_MUSIC) {
721        nativeStreamType = AudioSystem::MUSIC;
722    } else if (javaStreamType == javaAudioTrackFields.STREAM_ALARM) {
723        nativeStreamType = AudioSystem::ALARM;
724    } else if (javaStreamType == javaAudioTrackFields.STREAM_NOTIFICATION) {
725        nativeStreamType = AudioSystem::NOTIFICATION;
726    } else if (javaStreamType == javaAudioTrackFields.STREAM_BLUETOOTH_SCO) {
727        nativeStreamType = AudioSystem::BLUETOOTH_SCO;
728    } else {
729        nativeStreamType = AudioSystem::DEFAULT;
730    }
731
732    if (AudioSystem::getOutputSamplingRate(&afSamplingRate, nativeStreamType) != NO_ERROR) {
733        LOGE("AudioSystem::getOutputSamplingRate() for stream type %d failed in AudioTrack JNI",
734            nativeStreamType);
735        return DEFAULT_OUTPUT_SAMPLE_RATE;
736    } else {
737        return afSamplingRate;
738    }
739}
740
741
742// ----------------------------------------------------------------------------
743// returns the minimum required size for the successful creation of a streaming AudioTrack
744// returns -1 if there was an error querying the hardware.
745static jint android_media_AudioTrack_get_min_buff_size(JNIEnv *env,  jobject thiz,
746    jint sampleRateInHertz, jint nbChannels, jint audioFormat) {
747    int afSamplingRate;
748    int afFrameCount;
749    uint32_t afLatency;
750
751    if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) {
752        return -1;
753    }
754    if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) {
755        return -1;
756    }
757
758    if (AudioSystem::getOutputLatency(&afLatency) != NO_ERROR) {
759        return -1;
760    }
761
762    // Ensure that buffer depth covers at least audio hardware latency
763    uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSamplingRate);
764    if (minBufCount < 2) minBufCount = 2;
765    uint32_t minFrameCount = (afFrameCount*sampleRateInHertz*minBufCount)/afSamplingRate;
766    int minBuffSize = minFrameCount
767            * (audioFormat == javaAudioTrackFields.PCM16 ? 2 : 1)
768            * nbChannels;
769    return minBuffSize;
770}
771
772
773// ----------------------------------------------------------------------------
774// ----------------------------------------------------------------------------
775static JNINativeMethod gMethods[] = {
776    // name,              signature,     funcPtr
777    {"native_start",         "()V",      (void *)android_media_AudioTrack_start},
778    {"native_stop",          "()V",      (void *)android_media_AudioTrack_stop},
779    {"native_pause",         "()V",      (void *)android_media_AudioTrack_pause},
780    {"native_flush",         "()V",      (void *)android_media_AudioTrack_flush},
781    {"native_setup",         "(Ljava/lang/Object;IIIIII)I",
782                                         (void *)android_media_AudioTrack_native_setup},
783    {"native_finalize",      "()V",      (void *)android_media_AudioTrack_native_finalize},
784    {"native_release",       "()V",      (void *)android_media_AudioTrack_native_release},
785    {"native_write_byte",    "([BIII)I", (void *)android_media_AudioTrack_native_write},
786    {"native_write_short",   "([SIII)I", (void *)android_media_AudioTrack_native_write_short},
787    {"native_setVolume",     "(FF)V",    (void *)android_media_AudioTrack_set_volume},
788    {"native_get_native_frame_count",
789                             "()I",      (void *)android_media_AudioTrack_get_native_frame_count},
790    {"native_set_playback_rate",
791                             "(I)V",     (void *)android_media_AudioTrack_set_playback_rate},
792    {"native_get_playback_rate",
793                             "()I",      (void *)android_media_AudioTrack_get_playback_rate},
794    {"native_set_marker_pos","(I)I",     (void *)android_media_AudioTrack_set_marker_pos},
795    {"native_get_marker_pos","()I",      (void *)android_media_AudioTrack_get_marker_pos},
796    {"native_set_pos_update_period",
797                             "(I)I",     (void *)android_media_AudioTrack_set_pos_update_period},
798    {"native_get_pos_update_period",
799                             "()I",      (void *)android_media_AudioTrack_get_pos_update_period},
800    {"native_set_position",  "(I)I",     (void *)android_media_AudioTrack_set_position},
801    {"native_get_position",  "()I",      (void *)android_media_AudioTrack_get_position},
802    {"native_set_loop",      "(III)I",   (void *)android_media_AudioTrack_set_loop},
803    {"native_reload_static", "()I",      (void *)android_media_AudioTrack_reload},
804    {"native_get_output_sample_rate",
805                             "(I)I",      (void *)android_media_AudioTrack_get_output_sample_rate},
806    {"native_get_min_buff_size",
807                             "(III)I",   (void *)android_media_AudioTrack_get_min_buff_size},
808};
809
810
811// field names found in android/media/AudioTrack.java
812#define JAVA_POSTEVENT_CALLBACK_NAME                    "postEventFromNative"
813#define JAVA_CONST_PCM16_NAME                           "ENCODING_PCM_16BIT"
814#define JAVA_CONST_PCM8_NAME                            "ENCODING_PCM_8BIT"
815#define JAVA_CONST_BUFFER_COUNT_NAME                    "BUFFER_COUNT"
816#define JAVA_CONST_STREAM_VOICE_CALL_NAME               "STREAM_VOICE_CALL"
817#define JAVA_CONST_STREAM_SYSTEM_NAME                   "STREAM_SYSTEM"
818#define JAVA_CONST_STREAM_RING_NAME                     "STREAM_RING"
819#define JAVA_CONST_STREAM_MUSIC_NAME                    "STREAM_MUSIC"
820#define JAVA_CONST_STREAM_ALARM_NAME                    "STREAM_ALARM"
821#define JAVA_CONST_STREAM_NOTIFICATION_NAME             "STREAM_NOTIFICATION"
822#define JAVA_CONST_STREAM_BLUETOOTH_SCO_NAME            "STREAM_BLUETOOTH_SCO"
823#define JAVA_CONST_MODE_STREAM_NAME                     "MODE_STREAM"
824#define JAVA_CONST_MODE_STATIC_NAME                     "MODE_STATIC"
825#define JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME            "mNativeTrackInJavaObj"
826#define JAVA_JNIDATA_FIELD_NAME                         "mJniData"
827
828#define JAVA_AUDIOFORMAT_CLASS_NAME             "android/media/AudioFormat"
829#define JAVA_AUDIOMANAGER_CLASS_NAME            "android/media/AudioManager"
830
831// ----------------------------------------------------------------------------
832// preconditions:
833//    theClass is valid
834bool android_media_getIntConstantFromClass(JNIEnv* pEnv, jclass theClass, const char* className,
835                             const char* constName, int* constVal) {
836    jfieldID javaConst = NULL;
837    javaConst = pEnv->GetStaticFieldID(theClass, constName, "I");
838    if (javaConst != NULL) {
839        *constVal = pEnv->GetStaticIntField(theClass, javaConst);
840        return true;
841    } else {
842        LOGE("Can't find %s.%s", className, constName);
843        return false;
844    }
845}
846
847
848// ----------------------------------------------------------------------------
849int register_android_media_AudioTrack(JNIEnv *env)
850{
851    javaAudioTrackFields.audioTrackClass = NULL;
852    javaAudioTrackFields.nativeTrackInJavaObj = NULL;
853    javaAudioTrackFields.postNativeEventInJava = NULL;
854
855    // Get the AudioTrack class
856    javaAudioTrackFields.audioTrackClass = env->FindClass(kClassPathName);
857    if (javaAudioTrackFields.audioTrackClass == NULL) {
858        LOGE("Can't find %s", kClassPathName);
859        return -1;
860    }
861
862    // Get the postEvent method
863    javaAudioTrackFields.postNativeEventInJava = env->GetStaticMethodID(
864            javaAudioTrackFields.audioTrackClass,
865            JAVA_POSTEVENT_CALLBACK_NAME, "(Ljava/lang/Object;IIILjava/lang/Object;)V");
866    if (javaAudioTrackFields.postNativeEventInJava == NULL) {
867        LOGE("Can't find AudioTrack.%s", JAVA_POSTEVENT_CALLBACK_NAME);
868        return -1;
869    }
870
871    // Get the variables fields
872    //      nativeTrackInJavaObj
873    javaAudioTrackFields.nativeTrackInJavaObj = env->GetFieldID(
874            javaAudioTrackFields.audioTrackClass,
875            JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME, "I");
876    if (javaAudioTrackFields.nativeTrackInJavaObj == NULL) {
877        LOGE("Can't find AudioTrack.%s", JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME);
878        return -1;
879    }
880    //      jniData;
881    javaAudioTrackFields.jniData = env->GetFieldID(
882            javaAudioTrackFields.audioTrackClass,
883            JAVA_JNIDATA_FIELD_NAME, "I");
884    if (javaAudioTrackFields.jniData == NULL) {
885        LOGE("Can't find AudioTrack.%s", JAVA_JNIDATA_FIELD_NAME);
886        return -1;
887    }
888
889    // Get the memory mode constants
890    if ( !android_media_getIntConstantFromClass(env, javaAudioTrackFields.audioTrackClass,
891               kClassPathName,
892               JAVA_CONST_MODE_STATIC_NAME, &(javaAudioTrackFields.MODE_STATIC))
893         || !android_media_getIntConstantFromClass(env, javaAudioTrackFields.audioTrackClass,
894               kClassPathName,
895               JAVA_CONST_MODE_STREAM_NAME, &(javaAudioTrackFields.MODE_STREAM)) ) {
896        // error log performed in android_media_getIntConstantFromClass()
897        return -1;
898    }
899
900    // Get the format constants from the AudioFormat class
901    jclass audioFormatClass = NULL;
902    audioFormatClass = env->FindClass(JAVA_AUDIOFORMAT_CLASS_NAME);
903    if (audioFormatClass == NULL) {
904        LOGE("Can't find %s", JAVA_AUDIOFORMAT_CLASS_NAME);
905        return -1;
906    }
907    if ( !android_media_getIntConstantFromClass(env, audioFormatClass,
908                JAVA_AUDIOFORMAT_CLASS_NAME,
909                JAVA_CONST_PCM16_NAME, &(javaAudioTrackFields.PCM16))
910           || !android_media_getIntConstantFromClass(env, audioFormatClass,
911                JAVA_AUDIOFORMAT_CLASS_NAME,
912                JAVA_CONST_PCM8_NAME, &(javaAudioTrackFields.PCM8)) ) {
913        // error log performed in android_media_getIntConstantFromClass()
914        return -1;
915    }
916
917    // Get the stream types from the AudioManager class
918    jclass audioManagerClass = NULL;
919    audioManagerClass = env->FindClass(JAVA_AUDIOMANAGER_CLASS_NAME);
920    if (audioManagerClass == NULL) {
921       LOGE("Can't find %s", JAVA_AUDIOMANAGER_CLASS_NAME);
922       return -1;
923    }
924    if ( !android_media_getIntConstantFromClass(env, audioManagerClass,
925               JAVA_AUDIOMANAGER_CLASS_NAME,
926               JAVA_CONST_STREAM_VOICE_CALL_NAME, &(javaAudioTrackFields.STREAM_VOICE_CALL))
927          || !android_media_getIntConstantFromClass(env, audioManagerClass,
928               JAVA_AUDIOMANAGER_CLASS_NAME,
929               JAVA_CONST_STREAM_MUSIC_NAME, &(javaAudioTrackFields.STREAM_MUSIC))
930          || !android_media_getIntConstantFromClass(env, audioManagerClass,
931               JAVA_AUDIOMANAGER_CLASS_NAME,
932               JAVA_CONST_STREAM_SYSTEM_NAME, &(javaAudioTrackFields.STREAM_SYSTEM))
933          || !android_media_getIntConstantFromClass(env, audioManagerClass,
934               JAVA_AUDIOMANAGER_CLASS_NAME,
935               JAVA_CONST_STREAM_RING_NAME, &(javaAudioTrackFields.STREAM_RING))
936          || !android_media_getIntConstantFromClass(env, audioManagerClass,
937               JAVA_AUDIOMANAGER_CLASS_NAME,
938               JAVA_CONST_STREAM_ALARM_NAME, &(javaAudioTrackFields.STREAM_ALARM))
939          || !android_media_getIntConstantFromClass(env, audioManagerClass,
940               JAVA_AUDIOMANAGER_CLASS_NAME,
941               JAVA_CONST_STREAM_NOTIFICATION_NAME, &(javaAudioTrackFields.STREAM_NOTIFICATION))
942          || !android_media_getIntConstantFromClass(env, audioManagerClass,
943               JAVA_AUDIOMANAGER_CLASS_NAME,
944               JAVA_CONST_STREAM_BLUETOOTH_SCO_NAME,
945               &(javaAudioTrackFields.STREAM_BLUETOOTH_SCO))) {
946       // error log performed in android_media_getIntConstantFromClass()
947       return -1;
948    }
949
950    return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods));
951}
952
953
954// ----------------------------------------------------------------------------
955