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