android_media_AudioTrack.cpp revision 88e209dcf8c2ebddda5c272f46d1bd5478bc639c
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// ----------------------------------------------------------------------------
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 jint 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        return android_media_translateErrorCode(lpTrack->setSampleRate(sampleRateInHz));
549    } else {
550        jniThrowException(env, "java/lang/IllegalStateException",
551            "Unable to retrieve AudioTrack pointer for setSampleRate()");
552        return AUDIOTRACK_ERROR;
553    }
554}
555
556
557// ----------------------------------------------------------------------------
558static jint android_media_AudioTrack_get_playback_rate(JNIEnv *env,  jobject thiz) {
559    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
560                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
561
562    if (lpTrack) {
563        return (jint) lpTrack->getSampleRate();
564    } else {
565        jniThrowException(env, "java/lang/IllegalStateException",
566            "Unable to retrieve AudioTrack pointer for getSampleRate()");
567        return AUDIOTRACK_ERROR;
568    }
569}
570
571
572// ----------------------------------------------------------------------------
573static jint android_media_AudioTrack_set_marker_pos(JNIEnv *env,  jobject thiz,
574        jint markerPos) {
575
576    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
577                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
578
579    if (lpTrack) {
580        return android_media_translateErrorCode( lpTrack->setMarkerPosition(markerPos) );
581    } else {
582        jniThrowException(env, "java/lang/IllegalStateException",
583            "Unable to retrieve AudioTrack pointer for setMarkerPosition()");
584        return AUDIOTRACK_ERROR;
585    }
586}
587
588
589// ----------------------------------------------------------------------------
590static jint android_media_AudioTrack_get_marker_pos(JNIEnv *env,  jobject thiz) {
591
592    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
593                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
594    uint32_t markerPos = 0;
595
596    if (lpTrack) {
597        lpTrack->getMarkerPosition(&markerPos);
598        return (jint)markerPos;
599    } else {
600        jniThrowException(env, "java/lang/IllegalStateException",
601            "Unable to retrieve AudioTrack pointer for getMarkerPosition()");
602        return AUDIOTRACK_ERROR;
603    }
604}
605
606
607// ----------------------------------------------------------------------------
608static jint android_media_AudioTrack_set_pos_update_period(JNIEnv *env,  jobject thiz,
609        jint period) {
610
611    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
612                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
613
614    if (lpTrack) {
615        return android_media_translateErrorCode( lpTrack->setPositionUpdatePeriod(period) );
616    } else {
617        jniThrowException(env, "java/lang/IllegalStateException",
618            "Unable to retrieve AudioTrack pointer for setPositionUpdatePeriod()");
619        return AUDIOTRACK_ERROR;
620    }
621}
622
623
624// ----------------------------------------------------------------------------
625static jint android_media_AudioTrack_get_pos_update_period(JNIEnv *env,  jobject thiz) {
626
627    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
628                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
629    uint32_t period = 0;
630
631    if (lpTrack) {
632        lpTrack->getPositionUpdatePeriod(&period);
633        return (jint)period;
634    } else {
635        jniThrowException(env, "java/lang/IllegalStateException",
636            "Unable to retrieve AudioTrack pointer for getPositionUpdatePeriod()");
637        return AUDIOTRACK_ERROR;
638    }
639}
640
641
642// ----------------------------------------------------------------------------
643static jint android_media_AudioTrack_set_position(JNIEnv *env,  jobject thiz,
644        jint position) {
645
646    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
647                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
648
649    if (lpTrack) {
650        return android_media_translateErrorCode( lpTrack->setPosition(position) );
651    } else {
652        jniThrowException(env, "java/lang/IllegalStateException",
653            "Unable to retrieve AudioTrack pointer for setPosition()");
654        return AUDIOTRACK_ERROR;
655    }
656}
657
658
659// ----------------------------------------------------------------------------
660static jint android_media_AudioTrack_get_position(JNIEnv *env,  jobject thiz) {
661
662    AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
663                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
664    uint32_t position = 0;
665
666    if (lpTrack) {
667        lpTrack->getPosition(&position);
668        return (jint)position;
669    }  else {
670        jniThrowException(env, "java/lang/IllegalStateException",
671            "Unable to retrieve AudioTrack pointer for getPosition()");
672        return AUDIOTRACK_ERROR;
673    }
674}
675
676
677// ----------------------------------------------------------------------------
678static jint android_media_AudioTrack_set_loop(JNIEnv *env,  jobject thiz,
679        jint loopStart, jint loopEnd, jint loopCount) {
680
681     AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
682                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
683     if (lpTrack) {
684        return android_media_translateErrorCode( lpTrack->setLoop(loopStart, loopEnd, loopCount) );
685     }  else {
686        jniThrowException(env, "java/lang/IllegalStateException",
687            "Unable to retrieve AudioTrack pointer for setLoop()");
688        return AUDIOTRACK_ERROR;
689    }
690}
691
692
693// ----------------------------------------------------------------------------
694static jint android_media_AudioTrack_reload(JNIEnv *env,  jobject thiz) {
695
696     AudioTrack *lpTrack = (AudioTrack *)env->GetIntField(
697                thiz, javaAudioTrackFields.nativeTrackInJavaObj);
698     if (lpTrack) {
699        return android_media_translateErrorCode( lpTrack->reload() );
700     } else {
701        jniThrowException(env, "java/lang/IllegalStateException",
702            "Unable to retrieve AudioTrack pointer for reload()");
703        return AUDIOTRACK_ERROR;
704    }
705}
706
707
708// ----------------------------------------------------------------------------
709static jint android_media_AudioTrack_get_output_sample_rate(JNIEnv *env,  jobject thiz,
710        jint javaStreamType) {
711    int afSamplingRate;
712    // convert the stream type from Java to native value
713    // FIXME: code duplication with android_media_AudioTrack_native_setup()
714    AudioSystem::stream_type nativeStreamType;
715    if (javaStreamType == javaAudioTrackFields.STREAM_VOICE_CALL) {
716        nativeStreamType = AudioSystem::VOICE_CALL;
717    } else if (javaStreamType == javaAudioTrackFields.STREAM_SYSTEM) {
718        nativeStreamType = AudioSystem::SYSTEM;
719    } else if (javaStreamType == javaAudioTrackFields.STREAM_RING) {
720        nativeStreamType = AudioSystem::RING;
721    } else if (javaStreamType == javaAudioTrackFields.STREAM_MUSIC) {
722        nativeStreamType = AudioSystem::MUSIC;
723    } else if (javaStreamType == javaAudioTrackFields.STREAM_ALARM) {
724        nativeStreamType = AudioSystem::ALARM;
725    } else if (javaStreamType == javaAudioTrackFields.STREAM_NOTIFICATION) {
726        nativeStreamType = AudioSystem::NOTIFICATION;
727    } else if (javaStreamType == javaAudioTrackFields.STREAM_BLUETOOTH_SCO) {
728        nativeStreamType = AudioSystem::BLUETOOTH_SCO;
729    } else {
730        nativeStreamType = AudioSystem::DEFAULT;
731    }
732
733    if (AudioSystem::getOutputSamplingRate(&afSamplingRate, nativeStreamType) != NO_ERROR) {
734        LOGE("AudioSystem::getOutputSamplingRate() for stream type %d failed in AudioTrack JNI",
735            nativeStreamType);
736        return DEFAULT_OUTPUT_SAMPLE_RATE;
737    } else {
738        return afSamplingRate;
739    }
740}
741
742
743// ----------------------------------------------------------------------------
744// returns the minimum required size for the successful creation of a streaming AudioTrack
745// returns -1 if there was an error querying the hardware.
746static jint android_media_AudioTrack_get_min_buff_size(JNIEnv *env,  jobject thiz,
747    jint sampleRateInHertz, jint nbChannels, jint audioFormat) {
748    int afSamplingRate;
749    int afFrameCount;
750    uint32_t afLatency;
751
752    if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) {
753        return -1;
754    }
755    if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) {
756        return -1;
757    }
758
759    if (AudioSystem::getOutputLatency(&afLatency) != NO_ERROR) {
760        return -1;
761    }
762
763    // Ensure that buffer depth covers at least audio hardware latency
764    uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSamplingRate);
765    if (minBufCount < 2) minBufCount = 2;
766    uint32_t minFrameCount = (afFrameCount*sampleRateInHertz*minBufCount)/afSamplingRate;
767    int minBuffSize = minFrameCount
768            * (audioFormat == javaAudioTrackFields.PCM16 ? 2 : 1)
769            * nbChannels;
770    return minBuffSize;
771}
772
773
774// ----------------------------------------------------------------------------
775// ----------------------------------------------------------------------------
776static JNINativeMethod gMethods[] = {
777    // name,              signature,     funcPtr
778    {"native_start",         "()V",      (void *)android_media_AudioTrack_start},
779    {"native_stop",          "()V",      (void *)android_media_AudioTrack_stop},
780    {"native_pause",         "()V",      (void *)android_media_AudioTrack_pause},
781    {"native_flush",         "()V",      (void *)android_media_AudioTrack_flush},
782    {"native_setup",         "(Ljava/lang/Object;IIIIII)I",
783                                         (void *)android_media_AudioTrack_native_setup},
784    {"native_finalize",      "()V",      (void *)android_media_AudioTrack_native_finalize},
785    {"native_release",       "()V",      (void *)android_media_AudioTrack_native_release},
786    {"native_write_byte",    "([BIII)I", (void *)android_media_AudioTrack_native_write},
787    {"native_write_short",   "([SIII)I", (void *)android_media_AudioTrack_native_write_short},
788    {"native_setVolume",     "(FF)V",    (void *)android_media_AudioTrack_set_volume},
789    {"native_get_native_frame_count",
790                             "()I",      (void *)android_media_AudioTrack_get_native_frame_count},
791    {"native_set_playback_rate",
792                             "(I)I",     (void *)android_media_AudioTrack_set_playback_rate},
793    {"native_get_playback_rate",
794                             "()I",      (void *)android_media_AudioTrack_get_playback_rate},
795    {"native_set_marker_pos","(I)I",     (void *)android_media_AudioTrack_set_marker_pos},
796    {"native_get_marker_pos","()I",      (void *)android_media_AudioTrack_get_marker_pos},
797    {"native_set_pos_update_period",
798                             "(I)I",     (void *)android_media_AudioTrack_set_pos_update_period},
799    {"native_get_pos_update_period",
800                             "()I",      (void *)android_media_AudioTrack_get_pos_update_period},
801    {"native_set_position",  "(I)I",     (void *)android_media_AudioTrack_set_position},
802    {"native_get_position",  "()I",      (void *)android_media_AudioTrack_get_position},
803    {"native_set_loop",      "(III)I",   (void *)android_media_AudioTrack_set_loop},
804    {"native_reload_static", "()I",      (void *)android_media_AudioTrack_reload},
805    {"native_get_output_sample_rate",
806                             "(I)I",      (void *)android_media_AudioTrack_get_output_sample_rate},
807    {"native_get_min_buff_size",
808                             "(III)I",   (void *)android_media_AudioTrack_get_min_buff_size},
809};
810
811
812// field names found in android/media/AudioTrack.java
813#define JAVA_POSTEVENT_CALLBACK_NAME                    "postEventFromNative"
814#define JAVA_CONST_PCM16_NAME                           "ENCODING_PCM_16BIT"
815#define JAVA_CONST_PCM8_NAME                            "ENCODING_PCM_8BIT"
816#define JAVA_CONST_BUFFER_COUNT_NAME                    "BUFFER_COUNT"
817#define JAVA_CONST_STREAM_VOICE_CALL_NAME               "STREAM_VOICE_CALL"
818#define JAVA_CONST_STREAM_SYSTEM_NAME                   "STREAM_SYSTEM"
819#define JAVA_CONST_STREAM_RING_NAME                     "STREAM_RING"
820#define JAVA_CONST_STREAM_MUSIC_NAME                    "STREAM_MUSIC"
821#define JAVA_CONST_STREAM_ALARM_NAME                    "STREAM_ALARM"
822#define JAVA_CONST_STREAM_NOTIFICATION_NAME             "STREAM_NOTIFICATION"
823#define JAVA_CONST_STREAM_BLUETOOTH_SCO_NAME            "STREAM_BLUETOOTH_SCO"
824#define JAVA_CONST_MODE_STREAM_NAME                     "MODE_STREAM"
825#define JAVA_CONST_MODE_STATIC_NAME                     "MODE_STATIC"
826#define JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME            "mNativeTrackInJavaObj"
827#define JAVA_JNIDATA_FIELD_NAME                         "mJniData"
828
829#define JAVA_AUDIOFORMAT_CLASS_NAME             "android/media/AudioFormat"
830#define JAVA_AUDIOMANAGER_CLASS_NAME            "android/media/AudioManager"
831
832// ----------------------------------------------------------------------------
833// preconditions:
834//    theClass is valid
835bool android_media_getIntConstantFromClass(JNIEnv* pEnv, jclass theClass, const char* className,
836                             const char* constName, int* constVal) {
837    jfieldID javaConst = NULL;
838    javaConst = pEnv->GetStaticFieldID(theClass, constName, "I");
839    if (javaConst != NULL) {
840        *constVal = pEnv->GetStaticIntField(theClass, javaConst);
841        return true;
842    } else {
843        LOGE("Can't find %s.%s", className, constName);
844        return false;
845    }
846}
847
848
849// ----------------------------------------------------------------------------
850int register_android_media_AudioTrack(JNIEnv *env)
851{
852    javaAudioTrackFields.audioTrackClass = NULL;
853    javaAudioTrackFields.nativeTrackInJavaObj = NULL;
854    javaAudioTrackFields.postNativeEventInJava = NULL;
855
856    // Get the AudioTrack class
857    javaAudioTrackFields.audioTrackClass = env->FindClass(kClassPathName);
858    if (javaAudioTrackFields.audioTrackClass == NULL) {
859        LOGE("Can't find %s", kClassPathName);
860        return -1;
861    }
862
863    // Get the postEvent method
864    javaAudioTrackFields.postNativeEventInJava = env->GetStaticMethodID(
865            javaAudioTrackFields.audioTrackClass,
866            JAVA_POSTEVENT_CALLBACK_NAME, "(Ljava/lang/Object;IIILjava/lang/Object;)V");
867    if (javaAudioTrackFields.postNativeEventInJava == NULL) {
868        LOGE("Can't find AudioTrack.%s", JAVA_POSTEVENT_CALLBACK_NAME);
869        return -1;
870    }
871
872    // Get the variables fields
873    //      nativeTrackInJavaObj
874    javaAudioTrackFields.nativeTrackInJavaObj = env->GetFieldID(
875            javaAudioTrackFields.audioTrackClass,
876            JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME, "I");
877    if (javaAudioTrackFields.nativeTrackInJavaObj == NULL) {
878        LOGE("Can't find AudioTrack.%s", JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME);
879        return -1;
880    }
881    //      jniData;
882    javaAudioTrackFields.jniData = env->GetFieldID(
883            javaAudioTrackFields.audioTrackClass,
884            JAVA_JNIDATA_FIELD_NAME, "I");
885    if (javaAudioTrackFields.jniData == NULL) {
886        LOGE("Can't find AudioTrack.%s", JAVA_JNIDATA_FIELD_NAME);
887        return -1;
888    }
889
890    // Get the memory mode constants
891    if ( !android_media_getIntConstantFromClass(env, javaAudioTrackFields.audioTrackClass,
892               kClassPathName,
893               JAVA_CONST_MODE_STATIC_NAME, &(javaAudioTrackFields.MODE_STATIC))
894         || !android_media_getIntConstantFromClass(env, javaAudioTrackFields.audioTrackClass,
895               kClassPathName,
896               JAVA_CONST_MODE_STREAM_NAME, &(javaAudioTrackFields.MODE_STREAM)) ) {
897        // error log performed in android_media_getIntConstantFromClass()
898        return -1;
899    }
900
901    // Get the format constants from the AudioFormat class
902    jclass audioFormatClass = NULL;
903    audioFormatClass = env->FindClass(JAVA_AUDIOFORMAT_CLASS_NAME);
904    if (audioFormatClass == NULL) {
905        LOGE("Can't find %s", JAVA_AUDIOFORMAT_CLASS_NAME);
906        return -1;
907    }
908    if ( !android_media_getIntConstantFromClass(env, audioFormatClass,
909                JAVA_AUDIOFORMAT_CLASS_NAME,
910                JAVA_CONST_PCM16_NAME, &(javaAudioTrackFields.PCM16))
911           || !android_media_getIntConstantFromClass(env, audioFormatClass,
912                JAVA_AUDIOFORMAT_CLASS_NAME,
913                JAVA_CONST_PCM8_NAME, &(javaAudioTrackFields.PCM8)) ) {
914        // error log performed in android_media_getIntConstantFromClass()
915        return -1;
916    }
917
918    // Get the stream types from the AudioManager class
919    jclass audioManagerClass = NULL;
920    audioManagerClass = env->FindClass(JAVA_AUDIOMANAGER_CLASS_NAME);
921    if (audioManagerClass == NULL) {
922       LOGE("Can't find %s", JAVA_AUDIOMANAGER_CLASS_NAME);
923       return -1;
924    }
925    if ( !android_media_getIntConstantFromClass(env, audioManagerClass,
926               JAVA_AUDIOMANAGER_CLASS_NAME,
927               JAVA_CONST_STREAM_VOICE_CALL_NAME, &(javaAudioTrackFields.STREAM_VOICE_CALL))
928          || !android_media_getIntConstantFromClass(env, audioManagerClass,
929               JAVA_AUDIOMANAGER_CLASS_NAME,
930               JAVA_CONST_STREAM_MUSIC_NAME, &(javaAudioTrackFields.STREAM_MUSIC))
931          || !android_media_getIntConstantFromClass(env, audioManagerClass,
932               JAVA_AUDIOMANAGER_CLASS_NAME,
933               JAVA_CONST_STREAM_SYSTEM_NAME, &(javaAudioTrackFields.STREAM_SYSTEM))
934          || !android_media_getIntConstantFromClass(env, audioManagerClass,
935               JAVA_AUDIOMANAGER_CLASS_NAME,
936               JAVA_CONST_STREAM_RING_NAME, &(javaAudioTrackFields.STREAM_RING))
937          || !android_media_getIntConstantFromClass(env, audioManagerClass,
938               JAVA_AUDIOMANAGER_CLASS_NAME,
939               JAVA_CONST_STREAM_ALARM_NAME, &(javaAudioTrackFields.STREAM_ALARM))
940          || !android_media_getIntConstantFromClass(env, audioManagerClass,
941               JAVA_AUDIOMANAGER_CLASS_NAME,
942               JAVA_CONST_STREAM_NOTIFICATION_NAME, &(javaAudioTrackFields.STREAM_NOTIFICATION))
943          || !android_media_getIntConstantFromClass(env, audioManagerClass,
944               JAVA_AUDIOMANAGER_CLASS_NAME,
945               JAVA_CONST_STREAM_BLUETOOTH_SCO_NAME,
946               &(javaAudioTrackFields.STREAM_BLUETOOTH_SCO))) {
947       // error log performed in android_media_getIntConstantFromClass()
948       return -1;
949    }
950
951    return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods));
952}
953
954
955// ----------------------------------------------------------------------------
956