android_media_MediaPlayer2.cpp revision 1c2b64db02f62478dc62a6dae6764c1e08789975
1/*
2**
3** Copyright 2017, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18//#define LOG_NDEBUG 0
19#define LOG_TAG "MediaPlayer2-JNI"
20#include "utils/Log.h"
21
22#include <sys/stat.h>
23
24#include <media/AudioResamplerPublic.h>
25#include <media/DataSourceDesc.h>
26#include <media/MediaHTTPService.h>
27#include <media/MediaAnalyticsItem.h>
28#include <media/NdkWrapper.h>
29#include <media/stagefright/Utils.h>
30#include <media/stagefright/foundation/ByteUtils.h>  // for FOURCC definition
31#include <mediaplayer2/JAudioTrack.h>
32#include <mediaplayer2/mediaplayer2.h>
33#include <stdio.h>
34#include <assert.h>
35#include <limits.h>
36#include <unistd.h>
37#include <fcntl.h>
38#include <utils/threads.h>
39#include "jni.h"
40#include <nativehelper/JNIHelp.h>
41#include "android/native_window_jni.h"
42#include "android_runtime/Log.h"
43#include "utils/Errors.h"  // for status_t
44#include "utils/KeyedVector.h"
45#include "utils/String8.h"
46#include "android_media_BufferingParams.h"
47#include "android_media_Media2HTTPService.h"
48#include "android_media_Media2DataSource.h"
49#include "android_media_MediaMetricsJNI.h"
50#include "android_media_PlaybackParams.h"
51#include "android_media_SyncParams.h"
52#include "android_media_VolumeShaper.h"
53
54#include "android_os_Parcel.h"
55#include "android_util_Binder.h"
56#include <binder/Parcel.h>
57
58// Modular DRM begin
59#define FIND_CLASS(var, className) \
60var = env->FindClass(className); \
61LOG_FATAL_IF(! (var), "Unable to find class " className);
62
63#define GET_METHOD_ID(var, clazz, fieldName, fieldDescriptor) \
64var = env->GetMethodID(clazz, fieldName, fieldDescriptor); \
65LOG_FATAL_IF(! (var), "Unable to find method " fieldName);
66
67struct StateExceptionFields {
68    jmethodID init;
69    jclass classId;
70};
71
72static StateExceptionFields gStateExceptionFields;
73// Modular DRM end
74
75// ----------------------------------------------------------------------------
76
77using namespace android;
78
79using media::VolumeShaper;
80
81// ----------------------------------------------------------------------------
82
83struct fields_t {
84    jfieldID    context;
85    jfieldID    surface_texture;
86
87    jmethodID   post_event;
88
89    jmethodID   proxyConfigGetHost;
90    jmethodID   proxyConfigGetPort;
91    jmethodID   proxyConfigGetExclusionList;
92};
93static fields_t fields;
94
95static BufferingParams::fields_t gBufferingParamsFields;
96static PlaybackParams::fields_t gPlaybackParamsFields;
97static SyncParams::fields_t gSyncParamsFields;
98static VolumeShaperHelper::fields_t gVolumeShaperFields;
99
100static Mutex sLock;
101
102static bool ConvertKeyValueArraysToKeyedVector(
103        JNIEnv *env, jobjectArray keys, jobjectArray values,
104        KeyedVector<String8, String8>* keyedVector) {
105
106    int nKeyValuePairs = 0;
107    bool failed = false;
108    if (keys != NULL && values != NULL) {
109        nKeyValuePairs = env->GetArrayLength(keys);
110        failed = (nKeyValuePairs != env->GetArrayLength(values));
111    }
112
113    if (!failed) {
114        failed = ((keys != NULL && values == NULL) ||
115                  (keys == NULL && values != NULL));
116    }
117
118    if (failed) {
119        ALOGE("keys and values arrays have different length");
120        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
121        return false;
122    }
123
124    for (int i = 0; i < nKeyValuePairs; ++i) {
125        // No need to check on the ArrayIndexOutOfBoundsException, since
126        // it won't happen here.
127        jstring key = (jstring) env->GetObjectArrayElement(keys, i);
128        jstring value = (jstring) env->GetObjectArrayElement(values, i);
129
130        const char* keyStr = env->GetStringUTFChars(key, NULL);
131        if (!keyStr) {  // OutOfMemoryError
132            return false;
133        }
134
135        const char* valueStr = env->GetStringUTFChars(value, NULL);
136        if (!valueStr) {  // OutOfMemoryError
137            env->ReleaseStringUTFChars(key, keyStr);
138            return false;
139        }
140
141        keyedVector->add(String8(keyStr), String8(valueStr));
142
143        env->ReleaseStringUTFChars(key, keyStr);
144        env->ReleaseStringUTFChars(value, valueStr);
145        env->DeleteLocalRef(key);
146        env->DeleteLocalRef(value);
147    }
148    return true;
149}
150
151// ----------------------------------------------------------------------------
152// ref-counted object for callbacks
153class JNIMediaPlayer2Listener: public MediaPlayer2Listener
154{
155public:
156    JNIMediaPlayer2Listener(JNIEnv* env, jobject thiz, jobject weak_thiz);
157    ~JNIMediaPlayer2Listener();
158    virtual void notify(int64_t srcId, int msg, int ext1, int ext2,
159                        const Parcel *obj = NULL) override;
160private:
161    JNIMediaPlayer2Listener();
162    jclass      mClass;     // Reference to MediaPlayer2 class
163    jobject     mObject;    // Weak ref to MediaPlayer2 Java object to call on
164};
165
166JNIMediaPlayer2Listener::JNIMediaPlayer2Listener(JNIEnv* env, jobject thiz, jobject weak_thiz)
167{
168
169    // Hold onto the MediaPlayer2 class for use in calling the static method
170    // that posts events to the application thread.
171    jclass clazz = env->GetObjectClass(thiz);
172    if (clazz == NULL) {
173        ALOGE("Can't find android/media/MediaPlayer2Impl");
174        jniThrowException(env, "java/lang/Exception", NULL);
175        return;
176    }
177    mClass = (jclass)env->NewGlobalRef(clazz);
178
179    // We use a weak reference so the MediaPlayer2 object can be garbage collected.
180    // The reference is only used as a proxy for callbacks.
181    mObject  = env->NewGlobalRef(weak_thiz);
182}
183
184JNIMediaPlayer2Listener::~JNIMediaPlayer2Listener()
185{
186    // remove global references
187    JNIEnv *env = AndroidRuntime::getJNIEnv();
188    env->DeleteGlobalRef(mObject);
189    env->DeleteGlobalRef(mClass);
190}
191
192void JNIMediaPlayer2Listener::notify(int64_t srcId, int msg, int ext1, int ext2, const Parcel *obj)
193{
194    JNIEnv *env = AndroidRuntime::getJNIEnv();
195    if (obj && obj->dataSize() > 0) {
196        jobject jParcel = createJavaParcelObject(env);
197        if (jParcel != NULL) {
198            Parcel* nativeParcel = parcelForJavaObject(env, jParcel);
199            nativeParcel->setData(obj->data(), obj->dataSize());
200            env->CallStaticVoidMethod(mClass, fields.post_event, mObject,
201                    srcId, msg, ext1, ext2, jParcel);
202            env->DeleteLocalRef(jParcel);
203        }
204    } else {
205        env->CallStaticVoidMethod(mClass, fields.post_event, mObject,
206                srcId, msg, ext1, ext2, NULL);
207    }
208    if (env->ExceptionCheck()) {
209        ALOGW("An exception occurred while notifying an event.");
210        LOGW_EX(env);
211        env->ExceptionClear();
212    }
213}
214
215// ----------------------------------------------------------------------------
216
217static sp<MediaPlayer2> getMediaPlayer(JNIEnv* env, jobject thiz)
218{
219    Mutex::Autolock l(sLock);
220    MediaPlayer2* const p = (MediaPlayer2*)env->GetLongField(thiz, fields.context);
221    return sp<MediaPlayer2>(p);
222}
223
224static sp<MediaPlayer2> setMediaPlayer(JNIEnv* env, jobject thiz, const sp<MediaPlayer2>& player)
225{
226    Mutex::Autolock l(sLock);
227    sp<MediaPlayer2> old = (MediaPlayer2*)env->GetLongField(thiz, fields.context);
228    if (player.get()) {
229        player->incStrong((void*)setMediaPlayer);
230    }
231    if (old != 0) {
232        old->decStrong((void*)setMediaPlayer);
233    }
234    env->SetLongField(thiz, fields.context, (jlong)player.get());
235    return old;
236}
237
238// If exception is NULL and opStatus is not OK, this method sends an error
239// event to the client application; otherwise, if exception is not NULL and
240// opStatus is not OK, this method throws the given exception to the client
241// application.
242static void process_media_player_call(
243    JNIEnv *env, jobject thiz, status_t opStatus, const char* exception, const char *message)
244{
245    if (exception == NULL) {  // Don't throw exception. Instead, send an event.
246        if (opStatus != (status_t) OK) {
247            sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
248            if (mp != 0) {
249                int64_t srcId = 0;
250                mp->getSrcId(&srcId);
251                mp->notify(srcId, MEDIA2_ERROR, opStatus, 0);
252            }
253        }
254    } else {  // Throw exception!
255        if ( opStatus == (status_t) INVALID_OPERATION ) {
256            jniThrowException(env, "java/lang/IllegalStateException", NULL);
257        } else if ( opStatus == (status_t) BAD_VALUE ) {
258            jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
259        } else if ( opStatus == (status_t) PERMISSION_DENIED ) {
260            jniThrowException(env, "java/lang/SecurityException", NULL);
261        } else if ( opStatus != (status_t) OK ) {
262            if (strlen(message) > 230) {
263               // if the message is too long, don't bother displaying the status code
264               jniThrowException( env, exception, message);
265            } else {
266               char msg[256];
267                // append the status code to the message
268               sprintf(msg, "%s: status=0x%X", message, opStatus);
269               jniThrowException( env, exception, msg);
270            }
271        }
272    }
273}
274
275static void
276android_media_MediaPlayer2_handleDataSourceUrl(
277        JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId,
278        jobject httpServiceObj, jstring path, jobjectArray keys, jobjectArray values) {
279
280    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
281    if (mp == NULL) {
282        jniThrowException(env, "java/lang/IllegalStateException", NULL);
283        return;
284    }
285
286    if (path == NULL) {
287        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
288        return;
289    }
290
291    const char *tmp = env->GetStringUTFChars(path, NULL);
292    if (tmp == NULL) {  // Out of memory
293        return;
294    }
295    ALOGV("handleDataSourceUrl: path %s, srcId %lld", tmp, (long long)srcId);
296
297    if (strncmp(tmp, "content://", 10) == 0) {
298        ALOGE("handleDataSourceUrl: content scheme is not supported in native code");
299        jniThrowException(env, "java/io/IOException",
300                          "content scheme is not supported in native code");
301        return;
302    }
303
304    sp<DataSourceDesc> dsd = new DataSourceDesc();
305    dsd->mId = srcId;
306    dsd->mType = DataSourceDesc::TYPE_URL;
307    dsd->mUrl = tmp;
308
309    env->ReleaseStringUTFChars(path, tmp);
310    tmp = NULL;
311
312    // We build a KeyedVector out of the key and val arrays
313    if (!ConvertKeyValueArraysToKeyedVector(
314            env, keys, values, &dsd->mHeaders)) {
315        return;
316    }
317
318    sp<MediaHTTPService> httpService;
319    if (httpServiceObj != NULL) {
320        httpService = new JMedia2HTTPService(env, httpServiceObj);
321    }
322    dsd->mHttpService = httpService;
323
324    status_t err;
325    if (isCurrent) {
326        err = mp->setDataSource(dsd);
327    } else {
328        err = mp->prepareNextDataSource(dsd);
329    }
330    process_media_player_call(env, thiz, err,
331            "java/io/IOException", "handleDataSourceUrl failed." );
332}
333
334static void
335android_media_MediaPlayer2_handleDataSourceFD(
336    JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId,
337    jobject fileDescriptor, jlong offset, jlong length)
338{
339    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
340    if (mp == NULL ) {
341        jniThrowException(env, "java/lang/IllegalStateException", NULL);
342        return;
343    }
344
345    if (fileDescriptor == NULL) {
346        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
347        return;
348    }
349    int fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
350    ALOGV("handleDataSourceFD: srcId=%lld, fd=%d (%s), offset=%lld, length=%lld",
351          (long long)srcId, fd, nameForFd(fd).c_str(), (long long)offset, (long long)length);
352
353    struct stat sb;
354    int ret = fstat(fd, &sb);
355    if (ret != 0) {
356        ALOGE("handleDataSourceFD: fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
357        jniThrowException(env, "java/io/IOException", "handleDataSourceFD failed fstat");
358        return;
359    }
360
361    ALOGV("st_dev  = %llu", static_cast<unsigned long long>(sb.st_dev));
362    ALOGV("st_mode = %u", sb.st_mode);
363    ALOGV("st_uid  = %lu", static_cast<unsigned long>(sb.st_uid));
364    ALOGV("st_gid  = %lu", static_cast<unsigned long>(sb.st_gid));
365    ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
366
367    if (offset >= sb.st_size) {
368        ALOGE("handleDataSourceFD: offset is out of range");
369        jniThrowException(env, "java/lang/IllegalArgumentException",
370                          "handleDataSourceFD failed, offset is out of range.");
371        return;
372    }
373    if (offset + length > sb.st_size) {
374        length = sb.st_size - offset;
375        ALOGV("handleDataSourceFD: adjusted length = %lld", (long long)length);
376    }
377
378    sp<DataSourceDesc> dsd = new DataSourceDesc();
379    dsd->mId = srcId;
380    dsd->mType = DataSourceDesc::TYPE_FD;
381    dsd->mFD = fd;
382    dsd->mFDOffset = offset;
383    dsd->mFDLength = length;
384
385    status_t err;
386    if (isCurrent) {
387        err = mp->setDataSource(dsd);
388    } else {
389        err = mp->prepareNextDataSource(dsd);
390    }
391    process_media_player_call(env, thiz, err,
392            "java/io/IOException", "handleDataSourceFD failed." );
393}
394
395static void
396android_media_MediaPlayer2_handleDataSourceCallback(
397    JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId, jobject dataSource)
398{
399    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
400    if (mp == NULL ) {
401        jniThrowException(env, "java/lang/IllegalStateException", NULL);
402        return;
403    }
404
405    if (dataSource == NULL) {
406        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
407        return;
408    }
409    sp<DataSource> callbackDataSource = new JMedia2DataSource(env, dataSource);
410    sp<DataSourceDesc> dsd = new DataSourceDesc();
411    dsd->mId = srcId;
412    dsd->mType = DataSourceDesc::TYPE_CALLBACK;
413    dsd->mCallbackSource = callbackDataSource;
414
415    status_t err;
416    if (isCurrent) {
417        err = mp->setDataSource(dsd);
418    } else {
419        err = mp->prepareNextDataSource(dsd);
420    }
421    process_media_player_call(env, thiz, err,
422            "java/lang/RuntimeException", "handleDataSourceCallback failed." );
423}
424
425static sp<ANativeWindowWrapper>
426getVideoSurfaceTexture(JNIEnv* env, jobject thiz) {
427    ANativeWindow * const p = (ANativeWindow*)env->GetLongField(thiz, fields.surface_texture);
428    return new ANativeWindowWrapper(p);
429}
430
431static void
432decVideoSurfaceRef(JNIEnv *env, jobject thiz)
433{
434    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
435    if (mp == NULL) {
436        return;
437    }
438
439    ANativeWindow * const old_anw = (ANativeWindow*)env->GetLongField(thiz, fields.surface_texture);
440    if (old_anw != NULL) {
441        ANativeWindow_release(old_anw);
442        env->SetLongField(thiz, fields.surface_texture, (jlong)NULL);
443    }
444}
445
446static void
447setVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface, jboolean mediaPlayerMustBeAlive)
448{
449    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
450    if (mp == NULL) {
451        if (mediaPlayerMustBeAlive) {
452            jniThrowException(env, "java/lang/IllegalStateException", NULL);
453        }
454        return;
455    }
456
457    decVideoSurfaceRef(env, thiz);
458
459    ANativeWindow* anw = NULL;
460    if (jsurface) {
461        anw = ANativeWindow_fromSurface(env, jsurface);
462        if (anw == NULL) {
463            jniThrowException(env, "java/lang/IllegalArgumentException",
464                    "The surface has been released");
465            return;
466        }
467    }
468
469    env->SetLongField(thiz, fields.surface_texture, (jlong)anw);
470
471    // This will fail if the media player has not been initialized yet. This
472    // can be the case if setDisplay() on MediaPlayer2Impl.java has been called
473    // before setDataSource(). The redundant call to setVideoSurfaceTexture()
474    // in prepare/prepareAsync covers for this case.
475    mp->setVideoSurfaceTexture(new ANativeWindowWrapper(anw));
476}
477
478static void
479android_media_MediaPlayer2_setVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface)
480{
481    setVideoSurface(env, thiz, jsurface, true /* mediaPlayerMustBeAlive */);
482}
483
484static jobject
485android_media_MediaPlayer2_getBufferingParams(JNIEnv *env, jobject thiz)
486{
487    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
488    if (mp == NULL) {
489        jniThrowException(env, "java/lang/IllegalStateException", NULL);
490        return NULL;
491    }
492
493    BufferingParams bp;
494    BufferingSettings &settings = bp.settings;
495    process_media_player_call(
496            env, thiz, mp->getBufferingSettings(&settings),
497            "java/lang/IllegalStateException", "unexpected error");
498    ALOGV("getBufferingSettings:{%s}", settings.toString().string());
499
500    return bp.asJobject(env, gBufferingParamsFields);
501}
502
503static void
504android_media_MediaPlayer2_setBufferingParams(JNIEnv *env, jobject thiz, jobject params)
505{
506    if (params == NULL) {
507        return;
508    }
509
510    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
511    if (mp == NULL) {
512        jniThrowException(env, "java/lang/IllegalStateException", NULL);
513        return;
514    }
515
516    BufferingParams bp;
517    bp.fillFromJobject(env, gBufferingParamsFields, params);
518    ALOGV("setBufferingParams:{%s}", bp.settings.toString().string());
519
520    process_media_player_call(
521            env, thiz, mp->setBufferingSettings(bp.settings),
522            "java/lang/IllegalStateException", "unexpected error");
523}
524
525static void
526android_media_MediaPlayer2_playNextDataSource(JNIEnv *env, jobject thiz, jlong srcId)
527{
528    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
529    if (mp == NULL) {
530        jniThrowException(env, "java/lang/IllegalStateException", NULL);
531        return;
532    }
533
534    process_media_player_call(env, thiz, mp->playNextDataSource((int64_t)srcId),
535            "java/io/IOException", "playNextDataSource failed." );
536}
537
538static void
539android_media_MediaPlayer2_prepareAsync(JNIEnv *env, jobject thiz)
540{
541    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
542    if (mp == NULL ) {
543        jniThrowException(env, "java/lang/IllegalStateException", NULL);
544        return;
545    }
546
547    // Handle the case where the display surface was set before the mp was
548    // initialized. We try again to make it stick.
549    sp<ANativeWindowWrapper> st = getVideoSurfaceTexture(env, thiz);
550    mp->setVideoSurfaceTexture(st);
551
552    process_media_player_call( env, thiz, mp->prepareAsync(), "java/io/IOException", "Prepare Async failed." );
553}
554
555static void
556android_media_MediaPlayer2_start(JNIEnv *env, jobject thiz)
557{
558    ALOGV("start");
559    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
560    if (mp == NULL ) {
561        jniThrowException(env, "java/lang/IllegalStateException", NULL);
562        return;
563    }
564    process_media_player_call( env, thiz, mp->start(), NULL, NULL );
565}
566
567static void
568android_media_MediaPlayer2_stop(JNIEnv *env, jobject thiz)
569{
570    ALOGV("stop");
571    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
572    if (mp == NULL ) {
573        jniThrowException(env, "java/lang/IllegalStateException", NULL);
574        return;
575    }
576    process_media_player_call( env, thiz, mp->stop(), NULL, NULL );
577}
578
579static void
580android_media_MediaPlayer2_pause(JNIEnv *env, jobject thiz)
581{
582    ALOGV("pause");
583    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
584    if (mp == NULL ) {
585        jniThrowException(env, "java/lang/IllegalStateException", NULL);
586        return;
587    }
588    process_media_player_call( env, thiz, mp->pause(), NULL, NULL );
589}
590
591static jboolean
592android_media_MediaPlayer2_isPlaying(JNIEnv *env, jobject thiz)
593{
594    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
595    if (mp == NULL ) {
596        jniThrowException(env, "java/lang/IllegalStateException", NULL);
597        return JNI_FALSE;
598    }
599    const jboolean is_playing = mp->isPlaying();
600
601    ALOGV("isPlaying: %d", is_playing);
602    return is_playing;
603}
604
605static void
606android_media_MediaPlayer2_setPlaybackParams(JNIEnv *env, jobject thiz, jobject params)
607{
608    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
609    if (mp == NULL) {
610        jniThrowException(env, "java/lang/IllegalStateException", NULL);
611        return;
612    }
613
614    PlaybackParams pbp;
615    pbp.fillFromJobject(env, gPlaybackParamsFields, params);
616    ALOGV("setPlaybackParams: %d:%f %d:%f %d:%u %d:%u",
617            pbp.speedSet, pbp.audioRate.mSpeed,
618            pbp.pitchSet, pbp.audioRate.mPitch,
619            pbp.audioFallbackModeSet, pbp.audioRate.mFallbackMode,
620            pbp.audioStretchModeSet, pbp.audioRate.mStretchMode);
621
622    AudioPlaybackRate rate;
623    status_t err = mp->getPlaybackSettings(&rate);
624    if (err == OK) {
625        bool updatedRate = false;
626        if (pbp.speedSet) {
627            rate.mSpeed = pbp.audioRate.mSpeed;
628            updatedRate = true;
629        }
630        if (pbp.pitchSet) {
631            rate.mPitch = pbp.audioRate.mPitch;
632            updatedRate = true;
633        }
634        if (pbp.audioFallbackModeSet) {
635            rate.mFallbackMode = pbp.audioRate.mFallbackMode;
636            updatedRate = true;
637        }
638        if (pbp.audioStretchModeSet) {
639            rate.mStretchMode = pbp.audioRate.mStretchMode;
640            updatedRate = true;
641        }
642        if (updatedRate) {
643            err = mp->setPlaybackSettings(rate);
644        }
645    }
646    process_media_player_call(
647            env, thiz, err,
648            "java/lang/IllegalStateException", "unexpected error");
649}
650
651static jobject
652android_media_MediaPlayer2_getPlaybackParams(JNIEnv *env, jobject thiz)
653{
654    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
655    if (mp == NULL) {
656        jniThrowException(env, "java/lang/IllegalStateException", NULL);
657        return NULL;
658    }
659
660    PlaybackParams pbp;
661    AudioPlaybackRate &audioRate = pbp.audioRate;
662    process_media_player_call(
663            env, thiz, mp->getPlaybackSettings(&audioRate),
664            "java/lang/IllegalStateException", "unexpected error");
665    ALOGV("getPlaybackSettings: %f %f %d %d",
666            audioRate.mSpeed, audioRate.mPitch, audioRate.mFallbackMode, audioRate.mStretchMode);
667
668    pbp.speedSet = true;
669    pbp.pitchSet = true;
670    pbp.audioFallbackModeSet = true;
671    pbp.audioStretchModeSet = true;
672
673    return pbp.asJobject(env, gPlaybackParamsFields);
674}
675
676static void
677android_media_MediaPlayer2_setSyncParams(JNIEnv *env, jobject thiz, jobject params)
678{
679    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
680    if (mp == NULL) {
681        jniThrowException(env, "java/lang/IllegalStateException", NULL);
682        return;
683    }
684
685    SyncParams scp;
686    scp.fillFromJobject(env, gSyncParamsFields, params);
687    ALOGV("setSyncParams: %d:%d %d:%d %d:%f %d:%f",
688          scp.syncSourceSet, scp.sync.mSource,
689          scp.audioAdjustModeSet, scp.sync.mAudioAdjustMode,
690          scp.toleranceSet, scp.sync.mTolerance,
691          scp.frameRateSet, scp.frameRate);
692
693    AVSyncSettings avsync;
694    float videoFrameRate;
695    status_t err = mp->getSyncSettings(&avsync, &videoFrameRate);
696    if (err == OK) {
697        bool updatedSync = scp.frameRateSet;
698        if (scp.syncSourceSet) {
699            avsync.mSource = scp.sync.mSource;
700            updatedSync = true;
701        }
702        if (scp.audioAdjustModeSet) {
703            avsync.mAudioAdjustMode = scp.sync.mAudioAdjustMode;
704            updatedSync = true;
705        }
706        if (scp.toleranceSet) {
707            avsync.mTolerance = scp.sync.mTolerance;
708            updatedSync = true;
709        }
710        if (updatedSync) {
711            err = mp->setSyncSettings(avsync, scp.frameRateSet ? scp.frameRate : -1.f);
712        }
713    }
714    process_media_player_call(
715            env, thiz, err,
716            "java/lang/IllegalStateException", "unexpected error");
717}
718
719static jobject
720android_media_MediaPlayer2_getSyncParams(JNIEnv *env, jobject thiz)
721{
722    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
723    if (mp == NULL) {
724        jniThrowException(env, "java/lang/IllegalStateException", NULL);
725        return NULL;
726    }
727
728    SyncParams scp;
729    scp.frameRate = -1.f;
730    process_media_player_call(
731            env, thiz, mp->getSyncSettings(&scp.sync, &scp.frameRate),
732            "java/lang/IllegalStateException", "unexpected error");
733
734    ALOGV("getSyncSettings: %d %d %f %f",
735            scp.sync.mSource, scp.sync.mAudioAdjustMode, scp.sync.mTolerance, scp.frameRate);
736
737    // sanity check params
738    if (scp.sync.mSource >= AVSYNC_SOURCE_MAX
739            || scp.sync.mAudioAdjustMode >= AVSYNC_AUDIO_ADJUST_MODE_MAX
740            || scp.sync.mTolerance < 0.f
741            || scp.sync.mTolerance >= AVSYNC_TOLERANCE_MAX) {
742        jniThrowException(env,  "java/lang/IllegalStateException", NULL);
743        return NULL;
744    }
745
746    scp.syncSourceSet = true;
747    scp.audioAdjustModeSet = true;
748    scp.toleranceSet = true;
749    scp.frameRateSet = scp.frameRate >= 0.f;
750
751    return scp.asJobject(env, gSyncParamsFields);
752}
753
754static void
755android_media_MediaPlayer2_seekTo(JNIEnv *env, jobject thiz, jlong msec, jint mode)
756{
757    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
758    if (mp == NULL ) {
759        jniThrowException(env, "java/lang/IllegalStateException", NULL);
760        return;
761    }
762    ALOGV("seekTo: %lld(msec), mode=%d", (long long)msec, mode);
763    process_media_player_call( env, thiz, mp->seekTo((int)msec, (MediaPlayer2SeekMode)mode), NULL, NULL );
764}
765
766static void
767android_media_MediaPlayer2_notifyAt(JNIEnv *env, jobject thiz, jlong mediaTimeUs)
768{
769    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
770    if (mp == NULL) {
771        jniThrowException(env, "java/lang/IllegalStateException", NULL);
772        return;
773    }
774    ALOGV("notifyAt: %lld", (long long)mediaTimeUs);
775    process_media_player_call( env, thiz, mp->notifyAt((int64_t)mediaTimeUs), NULL, NULL );
776}
777
778static jint
779android_media_MediaPlayer2_getVideoWidth(JNIEnv *env, jobject thiz)
780{
781    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
782    if (mp == NULL ) {
783        jniThrowException(env, "java/lang/IllegalStateException", NULL);
784        return 0;
785    }
786    int w;
787    if (0 != mp->getVideoWidth(&w)) {
788        ALOGE("getVideoWidth failed");
789        w = 0;
790    }
791    ALOGV("getVideoWidth: %d", w);
792    return (jint) w;
793}
794
795static jint
796android_media_MediaPlayer2_getVideoHeight(JNIEnv *env, jobject thiz)
797{
798    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
799    if (mp == NULL ) {
800        jniThrowException(env, "java/lang/IllegalStateException", NULL);
801        return 0;
802    }
803    int h;
804    if (0 != mp->getVideoHeight(&h)) {
805        ALOGE("getVideoHeight failed");
806        h = 0;
807    }
808    ALOGV("getVideoHeight: %d", h);
809    return (jint) h;
810}
811
812static jobject
813android_media_MediaPlayer2_native_getMetrics(JNIEnv *env, jobject thiz)
814{
815    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
816    if (mp == NULL ) {
817        jniThrowException(env, "java/lang/IllegalStateException", NULL);
818        return 0;
819    }
820
821    Parcel p;
822    int key = FOURCC('m','t','r','X');
823    status_t status = mp->getParameter(key, &p);
824    if (status != OK) {
825        ALOGD("getMetrics() failed: %d", status);
826        return (jobject) NULL;
827    }
828
829    p.setDataPosition(0);
830    MediaAnalyticsItem *item = new MediaAnalyticsItem;
831    item->readFromParcel(p);
832    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item, NULL);
833
834    // housekeeping
835    delete item;
836    item = NULL;
837
838    return mybundle;
839}
840
841static jint
842android_media_MediaPlayer2_getCurrentPosition(JNIEnv *env, jobject thiz)
843{
844    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
845    if (mp == NULL ) {
846        jniThrowException(env, "java/lang/IllegalStateException", NULL);
847        return 0;
848    }
849    int msec;
850    process_media_player_call( env, thiz, mp->getCurrentPosition(&msec), NULL, NULL );
851    ALOGV("getCurrentPosition: %d (msec)", msec);
852    return (jint) msec;
853}
854
855static jint
856android_media_MediaPlayer2_getDuration(JNIEnv *env, jobject thiz)
857{
858    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
859    if (mp == NULL ) {
860        jniThrowException(env, "java/lang/IllegalStateException", NULL);
861        return 0;
862    }
863    int msec;
864    process_media_player_call( env, thiz, mp->getDuration(&msec), NULL, NULL );
865    ALOGV("getDuration: %d (msec)", msec);
866    return (jint) msec;
867}
868
869static void
870android_media_MediaPlayer2_reset(JNIEnv *env, jobject thiz)
871{
872    ALOGV("reset");
873    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
874    if (mp == NULL ) {
875        jniThrowException(env, "java/lang/IllegalStateException", NULL);
876        return;
877    }
878    process_media_player_call( env, thiz, mp->reset(), NULL, NULL );
879}
880
881static jint
882android_media_MediaPlayer2_getAudioStreamType(JNIEnv *env, jobject thiz)
883{
884    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
885    if (mp == NULL ) {
886        jniThrowException(env, "java/lang/IllegalStateException", NULL);
887        return 0;
888    }
889    audio_stream_type_t streamtype;
890    process_media_player_call( env, thiz, mp->getAudioStreamType(&streamtype), NULL, NULL );
891    ALOGV("getAudioStreamType: %d (streamtype)", streamtype);
892    return (jint) streamtype;
893}
894
895static jboolean
896android_media_MediaPlayer2_setParameter(JNIEnv *env, jobject thiz, jint key, jobject java_request)
897{
898    ALOGV("setParameter: key %d", key);
899    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
900    if (mp == NULL ) {
901        jniThrowException(env, "java/lang/IllegalStateException", NULL);
902        return false;
903    }
904
905    Parcel *request = parcelForJavaObject(env, java_request);
906    status_t err = mp->setParameter(key, *request);
907    if (err == OK) {
908        return true;
909    } else {
910        return false;
911    }
912}
913
914static void
915android_media_MediaPlayer2_setLooping(JNIEnv *env, jobject thiz, jboolean looping)
916{
917    ALOGV("setLooping: %d", looping);
918    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
919    if (mp == NULL ) {
920        jniThrowException(env, "java/lang/IllegalStateException", NULL);
921        return;
922    }
923    process_media_player_call( env, thiz, mp->setLooping(looping), NULL, NULL );
924}
925
926static jboolean
927android_media_MediaPlayer2_isLooping(JNIEnv *env, jobject thiz)
928{
929    ALOGV("isLooping");
930    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
931    if (mp == NULL ) {
932        jniThrowException(env, "java/lang/IllegalStateException", NULL);
933        return JNI_FALSE;
934    }
935    return mp->isLooping() ? JNI_TRUE : JNI_FALSE;
936}
937
938static void
939android_media_MediaPlayer2_setVolume(JNIEnv *env, jobject thiz, jfloat leftVolume, jfloat rightVolume)
940{
941    ALOGV("setVolume: left %f  right %f", (float) leftVolume, (float) rightVolume);
942    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
943    if (mp == NULL ) {
944        jniThrowException(env, "java/lang/IllegalStateException", NULL);
945        return;
946    }
947    process_media_player_call( env, thiz, mp->setVolume((float) leftVolume, (float) rightVolume), NULL, NULL );
948}
949
950// Sends the request and reply parcels to the media player via the
951// binder interface.
952static jint
953android_media_MediaPlayer2_invoke(JNIEnv *env, jobject thiz,
954                                 jobject java_request, jobject java_reply)
955{
956    sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
957    if (media_player == NULL ) {
958        jniThrowException(env, "java/lang/IllegalStateException", NULL);
959        return UNKNOWN_ERROR;
960    }
961
962    Parcel *request = parcelForJavaObject(env, java_request);
963    Parcel *reply = parcelForJavaObject(env, java_reply);
964
965    request->setDataPosition(0);
966
967    // Don't use process_media_player_call which use the async loop to
968    // report errors, instead returns the status.
969    return (jint) media_player->invoke(*request, reply);
970}
971
972// Sends the new filter to the client.
973static jint
974android_media_MediaPlayer2_setMetadataFilter(JNIEnv *env, jobject thiz, jobject request)
975{
976    sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
977    if (media_player == NULL ) {
978        jniThrowException(env, "java/lang/IllegalStateException", NULL);
979        return UNKNOWN_ERROR;
980    }
981
982    Parcel *filter = parcelForJavaObject(env, request);
983
984    if (filter == NULL ) {
985        jniThrowException(env, "java/lang/RuntimeException", "Filter is null");
986        return UNKNOWN_ERROR;
987    }
988
989    return (jint) media_player->setMetadataFilter(*filter);
990}
991
992static jboolean
993android_media_MediaPlayer2_getMetadata(JNIEnv *env, jobject thiz, jboolean update_only,
994                                      jboolean apply_filter, jobject reply)
995{
996    sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
997    if (media_player == NULL ) {
998        jniThrowException(env, "java/lang/IllegalStateException", NULL);
999        return JNI_FALSE;
1000    }
1001
1002    Parcel *metadata = parcelForJavaObject(env, reply);
1003
1004    if (metadata == NULL ) {
1005        jniThrowException(env, "java/lang/RuntimeException", "Reply parcel is null");
1006        return JNI_FALSE;
1007    }
1008
1009    metadata->freeData();
1010    // On return metadata is positioned at the beginning of the
1011    // metadata. Note however that the parcel actually starts with the
1012    // return code so you should not rewind the parcel using
1013    // setDataPosition(0).
1014    if (media_player->getMetadata(update_only, apply_filter, metadata) == OK) {
1015        return JNI_TRUE;
1016    } else {
1017        return JNI_FALSE;
1018    }
1019}
1020
1021// This function gets some field IDs, which in turn causes class initialization.
1022// It is called from a static block in MediaPlayer2, which won't run until the
1023// first time an instance of this class is used.
1024static void
1025android_media_MediaPlayer2_native_init(JNIEnv *env)
1026{
1027    jclass clazz;
1028
1029    clazz = env->FindClass("android/media/MediaPlayer2Impl");
1030    if (clazz == NULL) {
1031        return;
1032    }
1033
1034    fields.context = env->GetFieldID(clazz, "mNativeContext", "J");
1035    if (fields.context == NULL) {
1036        return;
1037    }
1038
1039    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
1040                                               "(Ljava/lang/Object;JIIILjava/lang/Object;)V");
1041    if (fields.post_event == NULL) {
1042        return;
1043    }
1044
1045    fields.surface_texture = env->GetFieldID(clazz, "mNativeSurfaceTexture", "J");
1046    if (fields.surface_texture == NULL) {
1047        return;
1048    }
1049
1050    env->DeleteLocalRef(clazz);
1051
1052    clazz = env->FindClass("android/net/ProxyInfo");
1053    if (clazz == NULL) {
1054        return;
1055    }
1056
1057    fields.proxyConfigGetHost =
1058        env->GetMethodID(clazz, "getHost", "()Ljava/lang/String;");
1059
1060    fields.proxyConfigGetPort =
1061        env->GetMethodID(clazz, "getPort", "()I");
1062
1063    fields.proxyConfigGetExclusionList =
1064        env->GetMethodID(clazz, "getExclusionListAsString", "()Ljava/lang/String;");
1065
1066    env->DeleteLocalRef(clazz);
1067
1068    gBufferingParamsFields.init(env);
1069
1070    // Modular DRM
1071    FIND_CLASS(clazz, "android/media/MediaDrm$MediaDrmStateException");
1072    if (clazz) {
1073        GET_METHOD_ID(gStateExceptionFields.init, clazz, "<init>", "(ILjava/lang/String;)V");
1074        gStateExceptionFields.classId = static_cast<jclass>(env->NewGlobalRef(clazz));
1075
1076        env->DeleteLocalRef(clazz);
1077    } else {
1078        ALOGE("JNI android_media_MediaPlayer2_native_init couldn't "
1079              "get clazz android/media/MediaDrm$MediaDrmStateException");
1080    }
1081
1082    gPlaybackParamsFields.init(env);
1083    gSyncParamsFields.init(env);
1084    gVolumeShaperFields.init(env);
1085}
1086
1087static void
1088android_media_MediaPlayer2_native_setup(JNIEnv *env, jobject thiz, jobject weak_this)
1089{
1090    ALOGV("native_setup");
1091    sp<MediaPlayer2> mp = MediaPlayer2::Create();
1092    if (mp == NULL) {
1093        jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
1094        return;
1095    }
1096
1097    // create new listener and give it to MediaPlayer2
1098    sp<JNIMediaPlayer2Listener> listener = new JNIMediaPlayer2Listener(env, thiz, weak_this);
1099    mp->setListener(listener);
1100
1101    // Stow our new C++ MediaPlayer2 in an opaque field in the Java object.
1102    setMediaPlayer(env, thiz, mp);
1103}
1104
1105static void
1106android_media_MediaPlayer2_release(JNIEnv *env, jobject thiz)
1107{
1108    ALOGV("release");
1109    decVideoSurfaceRef(env, thiz);
1110    sp<MediaPlayer2> mp = setMediaPlayer(env, thiz, 0);
1111    if (mp != NULL) {
1112        // this prevents native callbacks after the object is released
1113        mp->setListener(0);
1114        mp->disconnect();
1115    }
1116}
1117
1118static void
1119android_media_MediaPlayer2_native_finalize(JNIEnv *env, jobject thiz)
1120{
1121    ALOGV("native_finalize");
1122    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1123    if (mp != NULL) {
1124        ALOGW("MediaPlayer2 finalized without being released");
1125    }
1126    android_media_MediaPlayer2_release(env, thiz);
1127}
1128
1129static void android_media_MediaPlayer2_set_audio_session_id(JNIEnv *env,  jobject thiz,
1130        jint sessionId) {
1131    ALOGV("set_session_id(): %d", sessionId);
1132    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1133    if (mp == NULL ) {
1134        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1135        return;
1136    }
1137    process_media_player_call( env, thiz, mp->setAudioSessionId((audio_session_t) sessionId), NULL,
1138            NULL);
1139}
1140
1141static jint android_media_MediaPlayer2_get_audio_session_id(JNIEnv *env,  jobject thiz) {
1142    ALOGV("get_session_id()");
1143    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1144    if (mp == NULL ) {
1145        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1146        return 0;
1147    }
1148
1149    return (jint) mp->getAudioSessionId();
1150}
1151
1152static void
1153android_media_MediaPlayer2_setAuxEffectSendLevel(JNIEnv *env, jobject thiz, jfloat level)
1154{
1155    ALOGV("setAuxEffectSendLevel: level %f", level);
1156    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1157    if (mp == NULL ) {
1158        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1159        return;
1160    }
1161    process_media_player_call( env, thiz, mp->setAuxEffectSendLevel(level), NULL, NULL );
1162}
1163
1164static void android_media_MediaPlayer2_attachAuxEffect(JNIEnv *env,  jobject thiz, jint effectId) {
1165    ALOGV("attachAuxEffect(): %d", effectId);
1166    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1167    if (mp == NULL ) {
1168        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1169        return;
1170    }
1171    process_media_player_call( env, thiz, mp->attachAuxEffect(effectId), NULL, NULL );
1172}
1173
1174static void
1175android_media_MediaPlayer2_setNextMediaPlayer(JNIEnv *env, jobject thiz, jobject java_player)
1176{
1177    ALOGV("setNextMediaPlayer");
1178    sp<MediaPlayer2> thisplayer = getMediaPlayer(env, thiz);
1179    if (thisplayer == NULL) {
1180        jniThrowException(env, "java/lang/IllegalStateException", "This player not initialized");
1181        return;
1182    }
1183    sp<MediaPlayer2> nextplayer = (java_player == NULL) ? NULL : getMediaPlayer(env, java_player);
1184    if (nextplayer == NULL && java_player != NULL) {
1185        jniThrowException(env, "java/lang/IllegalStateException", "That player not initialized");
1186        return;
1187    }
1188
1189    if (nextplayer == thisplayer) {
1190        jniThrowException(env, "java/lang/IllegalArgumentException", "Next player can't be self");
1191        return;
1192    }
1193    // tie the two players together
1194    process_media_player_call(
1195            env, thiz, thisplayer->setNextMediaPlayer(nextplayer),
1196            "java/lang/IllegalArgumentException",
1197            "setNextMediaPlayer failed." );
1198    ;
1199}
1200
1201/////////////////////////////////////////////////////////////////////////////////////
1202// Modular DRM begin
1203
1204// TODO: investigate if these can be shared with their MediaDrm counterparts
1205static void throwDrmStateException(JNIEnv *env, const char *msg, status_t err)
1206{
1207    ALOGE("Illegal DRM state exception: %s (%d)", msg, err);
1208
1209    jobject exception = env->NewObject(gStateExceptionFields.classId,
1210            gStateExceptionFields.init, static_cast<int>(err),
1211            env->NewStringUTF(msg));
1212    env->Throw(static_cast<jthrowable>(exception));
1213}
1214
1215// TODO: investigate if these can be shared with their MediaDrm counterparts
1216static bool throwDrmExceptionAsNecessary(JNIEnv *env, status_t err, const char *msg = NULL)
1217{
1218    const char *drmMessage = "Unknown DRM Msg";
1219
1220    switch (err) {
1221    case ERROR_DRM_UNKNOWN:
1222        drmMessage = "General DRM error";
1223        break;
1224    case ERROR_DRM_NO_LICENSE:
1225        drmMessage = "No license";
1226        break;
1227    case ERROR_DRM_LICENSE_EXPIRED:
1228        drmMessage = "License expired";
1229        break;
1230    case ERROR_DRM_SESSION_NOT_OPENED:
1231        drmMessage = "Session not opened";
1232        break;
1233    case ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED:
1234        drmMessage = "Not initialized";
1235        break;
1236    case ERROR_DRM_DECRYPT:
1237        drmMessage = "Decrypt error";
1238        break;
1239    case ERROR_DRM_CANNOT_HANDLE:
1240        drmMessage = "Unsupported scheme or data format";
1241        break;
1242    case ERROR_DRM_TAMPER_DETECTED:
1243        drmMessage = "Invalid state";
1244        break;
1245    default:
1246        break;
1247    }
1248
1249    String8 vendorMessage;
1250    if (err >= ERROR_DRM_VENDOR_MIN && err <= ERROR_DRM_VENDOR_MAX) {
1251        vendorMessage = String8::format("DRM vendor-defined error: %d", err);
1252        drmMessage = vendorMessage.string();
1253    }
1254
1255    if (err == BAD_VALUE) {
1256        jniThrowException(env, "java/lang/IllegalArgumentException", msg);
1257        return true;
1258    } else if (err == ERROR_DRM_NOT_PROVISIONED) {
1259        jniThrowException(env, "android/media/NotProvisionedException", msg);
1260        return true;
1261    } else if (err == ERROR_DRM_RESOURCE_BUSY) {
1262        jniThrowException(env, "android/media/ResourceBusyException", msg);
1263        return true;
1264    } else if (err == ERROR_DRM_DEVICE_REVOKED) {
1265        jniThrowException(env, "android/media/DeniedByServerException", msg);
1266        return true;
1267    } else if (err == DEAD_OBJECT) {
1268        jniThrowException(env, "android/media/MediaDrmResetException",
1269                          "mediaserver died");
1270        return true;
1271    } else if (err != OK) {
1272        String8 errbuf;
1273        if (drmMessage != NULL) {
1274            if (msg == NULL) {
1275                msg = drmMessage;
1276            } else {
1277                errbuf = String8::format("%s: %s", msg, drmMessage);
1278                msg = errbuf.string();
1279            }
1280        }
1281        throwDrmStateException(env, msg, err);
1282        return true;
1283    }
1284    return false;
1285}
1286
1287static Vector<uint8_t> JByteArrayToVector(JNIEnv *env, jbyteArray const &byteArray)
1288{
1289    Vector<uint8_t> vector;
1290    size_t length = env->GetArrayLength(byteArray);
1291    vector.insertAt((size_t)0, length);
1292    env->GetByteArrayRegion(byteArray, 0, length, (jbyte *)vector.editArray());
1293    return vector;
1294}
1295
1296static void android_media_MediaPlayer2_prepareDrm(JNIEnv *env, jobject thiz,
1297                    jbyteArray uuidObj, jbyteArray drmSessionIdObj)
1298{
1299    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1300    if (mp == NULL) {
1301        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1302        return;
1303    }
1304
1305    if (uuidObj == NULL) {
1306        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
1307        return;
1308    }
1309
1310    Vector<uint8_t> uuid = JByteArrayToVector(env, uuidObj);
1311
1312    if (uuid.size() != 16) {
1313        jniThrowException(
1314                          env,
1315                          "java/lang/IllegalArgumentException",
1316                          "invalid UUID size, expected 16 bytes");
1317        return;
1318    }
1319
1320    Vector<uint8_t> drmSessionId = JByteArrayToVector(env, drmSessionIdObj);
1321
1322    if (drmSessionId.size() == 0) {
1323        jniThrowException(
1324                          env,
1325                          "java/lang/IllegalArgumentException",
1326                          "empty drmSessionId");
1327        return;
1328    }
1329
1330    status_t err = mp->prepareDrm(uuid.array(), drmSessionId);
1331    if (err != OK) {
1332        if (err == INVALID_OPERATION) {
1333            jniThrowException(
1334                              env,
1335                              "java/lang/IllegalStateException",
1336                              "The player must be in prepared state.");
1337        } else if (err == ERROR_DRM_CANNOT_HANDLE) {
1338            jniThrowException(
1339                              env,
1340                              "android/media/UnsupportedSchemeException",
1341                              "Failed to instantiate drm object.");
1342        } else {
1343            throwDrmExceptionAsNecessary(env, err, "Failed to prepare DRM scheme");
1344        }
1345    }
1346}
1347
1348static void android_media_MediaPlayer2_releaseDrm(JNIEnv *env, jobject thiz)
1349{
1350    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1351    if (mp == NULL ) {
1352        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1353        return;
1354    }
1355
1356    status_t err = mp->releaseDrm();
1357    if (err != OK) {
1358        if (err == INVALID_OPERATION) {
1359            jniThrowException(
1360                              env,
1361                              "java/lang/IllegalStateException",
1362                              "Can not release DRM in an active player state.");
1363        }
1364    }
1365}
1366// Modular DRM end
1367// ----------------------------------------------------------------------------
1368
1369/////////////////////////////////////////////////////////////////////////////////////
1370// AudioRouting begin
1371static jboolean android_media_MediaPlayer2_setOutputDevice(JNIEnv *env, jobject thiz, jint device_id)
1372{
1373    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1374    if (mp == NULL) {
1375        return false;
1376    }
1377    return mp->setOutputDevice(device_id) == NO_ERROR;
1378}
1379
1380static jint android_media_MediaPlayer2_getRoutedDeviceId(JNIEnv *env, jobject thiz)
1381{
1382    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1383    if (mp == NULL) {
1384        return AUDIO_PORT_HANDLE_NONE;
1385    }
1386    return mp->getRoutedDeviceId();
1387}
1388
1389static void android_media_MediaPlayer2_enableDeviceCallback(
1390        JNIEnv* env, jobject thiz, jboolean enabled)
1391{
1392    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1393    if (mp == NULL) {
1394        return;
1395    }
1396
1397    status_t status = mp->enableAudioDeviceCallback(enabled);
1398    if (status != NO_ERROR) {
1399        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1400        ALOGE("enable device callback failed: %d", status);
1401    }
1402}
1403
1404// AudioRouting end
1405// ----------------------------------------------------------------------------
1406
1407/////////////////////////////////////////////////////////////////////////////////////
1408// AudioTrack.StreamEventCallback begin
1409static void android_media_MediaPlayer2_native_on_tear_down(JNIEnv *env __unused,
1410        jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
1411{
1412    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
1413    if (callback != NULL) {
1414        callback(JAudioTrack::EVENT_NEW_IAUDIOTRACK, (void *) userDataPtr, NULL);
1415    }
1416}
1417
1418static void android_media_MediaPlayer2_native_on_stream_presentation_end(JNIEnv *env __unused,
1419        jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
1420{
1421    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
1422    if (callback != NULL) {
1423        callback(JAudioTrack::EVENT_STREAM_END, (void *) userDataPtr, NULL);
1424    }
1425}
1426
1427static void android_media_MediaPlayer2_native_on_stream_data_request(JNIEnv *env __unused,
1428        jobject thiz __unused, jlong jAudioTrackPtr, jlong callbackPtr, jlong userDataPtr)
1429{
1430    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
1431    JAudioTrack* track = (JAudioTrack *) jAudioTrackPtr;
1432    if (callback != NULL && track != NULL) {
1433        JAudioTrack::Buffer* buffer = new JAudioTrack::Buffer();
1434
1435        size_t bufferSizeInFrames = track->frameCount();
1436        audio_format_t format = track->format();
1437
1438        size_t bufferSizeInBytes;
1439        if (audio_has_proportional_frames(format)) {
1440            bufferSizeInBytes =
1441                    bufferSizeInFrames * audio_bytes_per_sample(format) * track->channelCount();
1442        } else {
1443            // See Javadoc of AudioTrack::getBufferSizeInFrames().
1444            bufferSizeInBytes = bufferSizeInFrames;
1445        }
1446
1447        uint8_t* byteBuffer = new uint8_t[bufferSizeInBytes];
1448        buffer->mSize = bufferSizeInBytes;
1449        buffer->mData = (void *) byteBuffer;
1450
1451        callback(JAudioTrack::EVENT_MORE_DATA, (void *) userDataPtr, buffer);
1452
1453        if (buffer->mSize > 0 && buffer->mData == byteBuffer) {
1454            track->write(buffer->mData, buffer->mSize, true /* Blocking */);
1455        }
1456
1457        delete[] byteBuffer;
1458        delete buffer;
1459    }
1460}
1461
1462
1463// AudioTrack.StreamEventCallback end
1464// ----------------------------------------------------------------------------
1465
1466static const JNINativeMethod gMethods[] = {
1467    {
1468        "nativeHandleDataSourceUrl",
1469        "(ZJLandroid/media/Media2HTTPService;Ljava/lang/String;[Ljava/lang/String;"
1470        "[Ljava/lang/String;)V",
1471        (void *)android_media_MediaPlayer2_handleDataSourceUrl
1472    },
1473    {
1474        "nativeHandleDataSourceFD",
1475        "(ZJLjava/io/FileDescriptor;JJ)V",
1476        (void *)android_media_MediaPlayer2_handleDataSourceFD
1477    },
1478    {
1479        "nativeHandleDataSourceCallback",
1480        "(ZJLandroid/media/Media2DataSource;)V",
1481        (void *)android_media_MediaPlayer2_handleDataSourceCallback
1482    },
1483    {"nativePlayNextDataSource", "(J)V",                        (void *)android_media_MediaPlayer2_playNextDataSource},
1484    {"_setVideoSurface",    "(Landroid/view/Surface;)V",        (void *)android_media_MediaPlayer2_setVideoSurface},
1485    {"getBufferingParams", "()Landroid/media/BufferingParams;", (void *)android_media_MediaPlayer2_getBufferingParams},
1486    {"setBufferingParams", "(Landroid/media/BufferingParams;)V", (void *)android_media_MediaPlayer2_setBufferingParams},
1487    {"prepareAsync",        "()V",                              (void *)android_media_MediaPlayer2_prepareAsync},
1488    {"_start",              "()V",                              (void *)android_media_MediaPlayer2_start},
1489    {"_stop",               "()V",                              (void *)android_media_MediaPlayer2_stop},
1490    {"getVideoWidth",       "()I",                              (void *)android_media_MediaPlayer2_getVideoWidth},
1491    {"getVideoHeight",      "()I",                              (void *)android_media_MediaPlayer2_getVideoHeight},
1492    {"native_getMetrics",   "()Landroid/os/PersistableBundle;", (void *)android_media_MediaPlayer2_native_getMetrics},
1493    {"setPlaybackParams", "(Landroid/media/PlaybackParams;)V", (void *)android_media_MediaPlayer2_setPlaybackParams},
1494    {"getPlaybackParams", "()Landroid/media/PlaybackParams;", (void *)android_media_MediaPlayer2_getPlaybackParams},
1495    {"setSyncParams",     "(Landroid/media/SyncParams;)V",  (void *)android_media_MediaPlayer2_setSyncParams},
1496    {"getSyncParams",     "()Landroid/media/SyncParams;",   (void *)android_media_MediaPlayer2_getSyncParams},
1497    {"_seekTo",             "(JI)V",                            (void *)android_media_MediaPlayer2_seekTo},
1498    {"_notifyAt",           "(J)V",                             (void *)android_media_MediaPlayer2_notifyAt},
1499    {"_pause",              "()V",                              (void *)android_media_MediaPlayer2_pause},
1500    {"isPlaying",           "()Z",                              (void *)android_media_MediaPlayer2_isPlaying},
1501    {"getCurrentPosition",  "()I",                              (void *)android_media_MediaPlayer2_getCurrentPosition},
1502    {"getDuration",         "()I",                              (void *)android_media_MediaPlayer2_getDuration},
1503    {"_release",            "()V",                              (void *)android_media_MediaPlayer2_release},
1504    {"_reset",              "()V",                              (void *)android_media_MediaPlayer2_reset},
1505    {"_getAudioStreamType", "()I",                              (void *)android_media_MediaPlayer2_getAudioStreamType},
1506    {"setParameter",        "(ILandroid/os/Parcel;)Z",          (void *)android_media_MediaPlayer2_setParameter},
1507    {"setLooping",          "(Z)V",                             (void *)android_media_MediaPlayer2_setLooping},
1508    {"isLooping",           "()Z",                              (void *)android_media_MediaPlayer2_isLooping},
1509    {"_setVolume",          "(FF)V",                            (void *)android_media_MediaPlayer2_setVolume},
1510    {"native_invoke",       "(Landroid/os/Parcel;Landroid/os/Parcel;)I",(void *)android_media_MediaPlayer2_invoke},
1511    {"native_setMetadataFilter", "(Landroid/os/Parcel;)I",      (void *)android_media_MediaPlayer2_setMetadataFilter},
1512    {"native_getMetadata", "(ZZLandroid/os/Parcel;)Z",          (void *)android_media_MediaPlayer2_getMetadata},
1513    {"native_init",         "()V",                              (void *)android_media_MediaPlayer2_native_init},
1514    {"native_setup",        "(Ljava/lang/Object;)V",            (void *)android_media_MediaPlayer2_native_setup},
1515    {"native_finalize",     "()V",                              (void *)android_media_MediaPlayer2_native_finalize},
1516    {"getAudioSessionId",   "()I",                              (void *)android_media_MediaPlayer2_get_audio_session_id},
1517    {"setAudioSessionId",   "(I)V",                             (void *)android_media_MediaPlayer2_set_audio_session_id},
1518    {"_setAuxEffectSendLevel", "(F)V",                          (void *)android_media_MediaPlayer2_setAuxEffectSendLevel},
1519    {"attachAuxEffect",     "(I)V",                             (void *)android_media_MediaPlayer2_attachAuxEffect},
1520    {"setNextMediaPlayer",  "(Landroid/media/MediaPlayer2;)V",  (void *)android_media_MediaPlayer2_setNextMediaPlayer},
1521    // Modular DRM
1522    { "_prepareDrm", "([B[B)V",                                 (void *)android_media_MediaPlayer2_prepareDrm },
1523    { "_releaseDrm", "()V",                                     (void *)android_media_MediaPlayer2_releaseDrm },
1524
1525    // AudioRouting
1526    {"native_setOutputDevice", "(I)Z",                          (void *)android_media_MediaPlayer2_setOutputDevice},
1527    {"native_getRoutedDeviceId", "()I",                         (void *)android_media_MediaPlayer2_getRoutedDeviceId},
1528    {"native_enableDeviceCallback", "(Z)V",                     (void *)android_media_MediaPlayer2_enableDeviceCallback},
1529
1530    // StreamEventCallback for JAudioTrack
1531    {"native_stream_event_onTearDown",                "(JJ)V",  (void *)android_media_MediaPlayer2_native_on_tear_down},
1532    {"native_stream_event_onStreamPresentationEnd",   "(JJ)V",  (void *)android_media_MediaPlayer2_native_on_stream_presentation_end},
1533    {"native_stream_event_onStreamDataRequest",       "(JJJ)V", (void *)android_media_MediaPlayer2_native_on_stream_data_request},
1534};
1535
1536// This function only registers the native methods
1537static int register_android_media_MediaPlayer2Impl(JNIEnv *env)
1538{
1539    return AndroidRuntime::registerNativeMethods(env,
1540                "android/media/MediaPlayer2Impl", gMethods, NELEM(gMethods));
1541}
1542
1543jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
1544{
1545    JNIEnv* env = NULL;
1546    jint result = -1;
1547
1548    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
1549        ALOGE("ERROR: GetEnv failed\n");
1550        goto bail;
1551    }
1552    assert(env != NULL);
1553
1554    if (register_android_media_MediaPlayer2Impl(env) < 0) {
1555        ALOGE("ERROR: MediaPlayer2 native registration failed\n");
1556        goto bail;
1557    }
1558
1559    /* success -- return valid version number */
1560    result = JNI_VERSION_1_4;
1561
1562bail:
1563    return result;
1564}
1565
1566// KTHXBYE
1567