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