android_media_MediaPlayer2.cpp revision adf77a01e8142a5abb496997beddead7b48f43b7
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/prepare 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_prepare(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((int64_t)msec, (MediaPlayer2SeekMode)mode),
764                              NULL, NULL);
765}
766
767static void
768android_media_MediaPlayer2_notifyAt(JNIEnv *env, jobject thiz, jlong mediaTimeUs)
769{
770    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
771    if (mp == NULL) {
772        jniThrowException(env, "java/lang/IllegalStateException", NULL);
773        return;
774    }
775    ALOGV("notifyAt: %lld", (long long)mediaTimeUs);
776    process_media_player_call( env, thiz, mp->notifyAt((int64_t)mediaTimeUs), NULL, NULL );
777}
778
779static jint
780android_media_MediaPlayer2_getMediaPlayer2State(JNIEnv *env, jobject thiz)
781{
782    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
783    if (mp == NULL) {
784        return MEDIAPLAYER2_STATE_IDLE;
785    }
786    return (jint)mp->getMediaPlayer2State();
787}
788
789static jint
790android_media_MediaPlayer2_getVideoWidth(JNIEnv *env, jobject thiz)
791{
792    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
793    if (mp == NULL ) {
794        jniThrowException(env, "java/lang/IllegalStateException", NULL);
795        return 0;
796    }
797    int w;
798    if (0 != mp->getVideoWidth(&w)) {
799        ALOGE("getVideoWidth failed");
800        w = 0;
801    }
802    ALOGV("getVideoWidth: %d", w);
803    return (jint) w;
804}
805
806static jint
807android_media_MediaPlayer2_getVideoHeight(JNIEnv *env, jobject thiz)
808{
809    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
810    if (mp == NULL ) {
811        jniThrowException(env, "java/lang/IllegalStateException", NULL);
812        return 0;
813    }
814    int h;
815    if (0 != mp->getVideoHeight(&h)) {
816        ALOGE("getVideoHeight failed");
817        h = 0;
818    }
819    ALOGV("getVideoHeight: %d", h);
820    return (jint) h;
821}
822
823static jobject
824android_media_MediaPlayer2_native_getMetrics(JNIEnv *env, jobject thiz)
825{
826    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
827    if (mp == NULL ) {
828        jniThrowException(env, "java/lang/IllegalStateException", NULL);
829        return 0;
830    }
831
832    Parcel p;
833    int key = FOURCC('m','t','r','X');
834    status_t status = mp->getParameter(key, &p);
835    if (status != OK) {
836        ALOGD("getMetrics() failed: %d", status);
837        return (jobject) NULL;
838    }
839
840    p.setDataPosition(0);
841    MediaAnalyticsItem *item = new MediaAnalyticsItem;
842    item->readFromParcel(p);
843    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item, NULL);
844
845    // housekeeping
846    delete item;
847    item = NULL;
848
849    return mybundle;
850}
851
852static jlong
853android_media_MediaPlayer2_getCurrentPosition(JNIEnv *env, jobject thiz)
854{
855    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
856    if (mp == NULL ) {
857        jniThrowException(env, "java/lang/IllegalStateException", NULL);
858        return 0;
859    }
860    int64_t msec;
861    process_media_player_call( env, thiz, mp->getCurrentPosition(&msec), NULL, NULL );
862    ALOGV("getCurrentPosition: %lld (msec)", (long long)msec);
863    return (jlong) msec;
864}
865
866static jlong
867android_media_MediaPlayer2_getDuration(JNIEnv *env, jobject thiz)
868{
869    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
870    if (mp == NULL ) {
871        jniThrowException(env, "java/lang/IllegalStateException", NULL);
872        return 0;
873    }
874    int64_t msec;
875    process_media_player_call( env, thiz, mp->getDuration(&msec), NULL, NULL );
876    ALOGV("getDuration: %lld (msec)", (long long)msec);
877    return (jlong) msec;
878}
879
880static void
881android_media_MediaPlayer2_reset(JNIEnv *env, jobject thiz)
882{
883    ALOGV("reset");
884    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
885    if (mp == NULL ) {
886        jniThrowException(env, "java/lang/IllegalStateException", NULL);
887        return;
888    }
889    process_media_player_call( env, thiz, mp->reset(), NULL, NULL );
890}
891
892static jint
893android_media_MediaPlayer2_getAudioStreamType(JNIEnv *env, jobject thiz)
894{
895    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
896    if (mp == NULL ) {
897        jniThrowException(env, "java/lang/IllegalStateException", NULL);
898        return 0;
899    }
900    audio_stream_type_t streamtype;
901    process_media_player_call( env, thiz, mp->getAudioStreamType(&streamtype), NULL, NULL );
902    ALOGV("getAudioStreamType: %d (streamtype)", streamtype);
903    return (jint) streamtype;
904}
905
906static jboolean
907android_media_MediaPlayer2_setParameter(JNIEnv *env, jobject thiz, jint key, jobject java_request)
908{
909    ALOGV("setParameter: key %d", key);
910    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
911    if (mp == NULL ) {
912        jniThrowException(env, "java/lang/IllegalStateException", NULL);
913        return false;
914    }
915
916    Parcel *request = parcelForJavaObject(env, java_request);
917    status_t err = mp->setParameter(key, *request);
918    if (err == OK) {
919        return true;
920    } else {
921        return false;
922    }
923}
924
925static jobject
926android_media_MediaPlayer2_getParameter(JNIEnv *env, jobject thiz, jint key)
927{
928    ALOGV("getParameter: key %d", key);
929    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
930    if (mp == NULL) {
931        jniThrowException(env, "java/lang/IllegalStateException", NULL);
932        return NULL;
933    }
934
935    jobject jParcel = createJavaParcelObject(env);
936    if (jParcel != NULL) {
937        Parcel* nativeParcel = parcelForJavaObject(env, jParcel);
938        status_t err = mp->getParameter(key, nativeParcel);
939        if (err != OK) {
940            env->DeleteLocalRef(jParcel);
941            return NULL;
942        }
943    }
944    return jParcel;
945}
946
947static void
948android_media_MediaPlayer2_setLooping(JNIEnv *env, jobject thiz, jboolean looping)
949{
950    ALOGV("setLooping: %d", looping);
951    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
952    if (mp == NULL ) {
953        jniThrowException(env, "java/lang/IllegalStateException", NULL);
954        return;
955    }
956    process_media_player_call( env, thiz, mp->setLooping(looping), NULL, NULL );
957}
958
959static jboolean
960android_media_MediaPlayer2_isLooping(JNIEnv *env, jobject thiz)
961{
962    ALOGV("isLooping");
963    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
964    if (mp == NULL ) {
965        jniThrowException(env, "java/lang/IllegalStateException", NULL);
966        return JNI_FALSE;
967    }
968    return mp->isLooping() ? JNI_TRUE : JNI_FALSE;
969}
970
971static void
972android_media_MediaPlayer2_setVolume(JNIEnv *env, jobject thiz, jfloat leftVolume, jfloat rightVolume)
973{
974    ALOGV("setVolume: left %f  right %f", (float) leftVolume, (float) rightVolume);
975    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
976    if (mp == NULL ) {
977        jniThrowException(env, "java/lang/IllegalStateException", NULL);
978        return;
979    }
980    process_media_player_call( env, thiz, mp->setVolume((float) leftVolume, (float) rightVolume), NULL, NULL );
981}
982
983// Sends the request and reply parcels to the media player via the
984// binder interface.
985static jint
986android_media_MediaPlayer2_invoke(JNIEnv *env, jobject thiz,
987                                 jobject java_request, jobject java_reply)
988{
989    sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
990    if (media_player == NULL ) {
991        jniThrowException(env, "java/lang/IllegalStateException", NULL);
992        return UNKNOWN_ERROR;
993    }
994
995    Parcel *request = parcelForJavaObject(env, java_request);
996    Parcel *reply = parcelForJavaObject(env, java_reply);
997
998    request->setDataPosition(0);
999
1000    // Don't use process_media_player_call which use the async loop to
1001    // report errors, instead returns the status.
1002    return (jint) media_player->invoke(*request, reply);
1003}
1004
1005// Sends the new filter to the client.
1006static jint
1007android_media_MediaPlayer2_setMetadataFilter(JNIEnv *env, jobject thiz, jobject request)
1008{
1009    sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
1010    if (media_player == NULL ) {
1011        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1012        return UNKNOWN_ERROR;
1013    }
1014
1015    Parcel *filter = parcelForJavaObject(env, request);
1016
1017    if (filter == NULL ) {
1018        jniThrowException(env, "java/lang/RuntimeException", "Filter is null");
1019        return UNKNOWN_ERROR;
1020    }
1021
1022    return (jint) media_player->setMetadataFilter(*filter);
1023}
1024
1025static jboolean
1026android_media_MediaPlayer2_getMetadata(JNIEnv *env, jobject thiz, jboolean update_only,
1027                                      jboolean apply_filter, jobject reply)
1028{
1029    sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
1030    if (media_player == NULL ) {
1031        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1032        return JNI_FALSE;
1033    }
1034
1035    Parcel *metadata = parcelForJavaObject(env, reply);
1036
1037    if (metadata == NULL ) {
1038        jniThrowException(env, "java/lang/RuntimeException", "Reply parcel is null");
1039        return JNI_FALSE;
1040    }
1041
1042    metadata->freeData();
1043    // On return metadata is positioned at the beginning of the
1044    // metadata. Note however that the parcel actually starts with the
1045    // return code so you should not rewind the parcel using
1046    // setDataPosition(0).
1047    if (media_player->getMetadata(update_only, apply_filter, metadata) == OK) {
1048        return JNI_TRUE;
1049    } else {
1050        return JNI_FALSE;
1051    }
1052}
1053
1054// This function gets some field IDs, which in turn causes class initialization.
1055// It is called from a static block in MediaPlayer2, which won't run until the
1056// first time an instance of this class is used.
1057static void
1058android_media_MediaPlayer2_native_init(JNIEnv *env)
1059{
1060    jclass clazz;
1061
1062    clazz = env->FindClass("android/media/MediaPlayer2Impl");
1063    if (clazz == NULL) {
1064        return;
1065    }
1066
1067    fields.context = env->GetFieldID(clazz, "mNativeContext", "J");
1068    if (fields.context == NULL) {
1069        return;
1070    }
1071
1072    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
1073                                               "(Ljava/lang/Object;JIIILjava/lang/Object;)V");
1074    if (fields.post_event == NULL) {
1075        return;
1076    }
1077
1078    fields.surface_texture = env->GetFieldID(clazz, "mNativeSurfaceTexture", "J");
1079    if (fields.surface_texture == NULL) {
1080        return;
1081    }
1082
1083    env->DeleteLocalRef(clazz);
1084
1085    clazz = env->FindClass("android/net/ProxyInfo");
1086    if (clazz == NULL) {
1087        return;
1088    }
1089
1090    fields.proxyConfigGetHost =
1091        env->GetMethodID(clazz, "getHost", "()Ljava/lang/String;");
1092
1093    fields.proxyConfigGetPort =
1094        env->GetMethodID(clazz, "getPort", "()I");
1095
1096    fields.proxyConfigGetExclusionList =
1097        env->GetMethodID(clazz, "getExclusionListAsString", "()Ljava/lang/String;");
1098
1099    env->DeleteLocalRef(clazz);
1100
1101    gBufferingParamsFields.init(env);
1102
1103    // Modular DRM
1104    FIND_CLASS(clazz, "android/media/MediaDrm$MediaDrmStateException");
1105    if (clazz) {
1106        GET_METHOD_ID(gStateExceptionFields.init, clazz, "<init>", "(ILjava/lang/String;)V");
1107        gStateExceptionFields.classId = static_cast<jclass>(env->NewGlobalRef(clazz));
1108
1109        env->DeleteLocalRef(clazz);
1110    } else {
1111        ALOGE("JNI android_media_MediaPlayer2_native_init couldn't "
1112              "get clazz android/media/MediaDrm$MediaDrmStateException");
1113    }
1114
1115    gPlaybackParamsFields.init(env);
1116    gSyncParamsFields.init(env);
1117    gVolumeShaperFields.init(env);
1118}
1119
1120static void
1121android_media_MediaPlayer2_native_setup(JNIEnv *env, jobject thiz, jobject weak_this)
1122{
1123    ALOGV("native_setup");
1124    sp<MediaPlayer2> mp = MediaPlayer2::Create();
1125    if (mp == NULL) {
1126        jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
1127        return;
1128    }
1129
1130    // create new listener and give it to MediaPlayer2
1131    sp<JNIMediaPlayer2Listener> listener = new JNIMediaPlayer2Listener(env, thiz, weak_this);
1132    mp->setListener(listener);
1133
1134    // Stow our new C++ MediaPlayer2 in an opaque field in the Java object.
1135    setMediaPlayer(env, thiz, mp);
1136}
1137
1138static void
1139android_media_MediaPlayer2_release(JNIEnv *env, jobject thiz)
1140{
1141    ALOGV("release");
1142    decVideoSurfaceRef(env, thiz);
1143    sp<MediaPlayer2> mp = setMediaPlayer(env, thiz, 0);
1144    if (mp != NULL) {
1145        // this prevents native callbacks after the object is released
1146        mp->setListener(0);
1147        mp->disconnect();
1148    }
1149}
1150
1151static void
1152android_media_MediaPlayer2_native_finalize(JNIEnv *env, jobject thiz)
1153{
1154    ALOGV("native_finalize");
1155    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1156    if (mp != NULL) {
1157        ALOGW("MediaPlayer2 finalized without being released");
1158    }
1159    android_media_MediaPlayer2_release(env, thiz);
1160}
1161
1162static void android_media_MediaPlayer2_set_audio_session_id(JNIEnv *env,  jobject thiz,
1163        jint sessionId) {
1164    ALOGV("set_session_id(): %d", sessionId);
1165    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1166    if (mp == NULL ) {
1167        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1168        return;
1169    }
1170    process_media_player_call( env, thiz, mp->setAudioSessionId((audio_session_t) sessionId), NULL,
1171            NULL);
1172}
1173
1174static jint android_media_MediaPlayer2_get_audio_session_id(JNIEnv *env,  jobject thiz) {
1175    ALOGV("get_session_id()");
1176    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1177    if (mp == NULL ) {
1178        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1179        return 0;
1180    }
1181
1182    return (jint) mp->getAudioSessionId();
1183}
1184
1185static void
1186android_media_MediaPlayer2_setAuxEffectSendLevel(JNIEnv *env, jobject thiz, jfloat level)
1187{
1188    ALOGV("setAuxEffectSendLevel: level %f", level);
1189    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1190    if (mp == NULL ) {
1191        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1192        return;
1193    }
1194    process_media_player_call( env, thiz, mp->setAuxEffectSendLevel(level), NULL, NULL );
1195}
1196
1197static void android_media_MediaPlayer2_attachAuxEffect(JNIEnv *env,  jobject thiz, jint effectId) {
1198    ALOGV("attachAuxEffect(): %d", effectId);
1199    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1200    if (mp == NULL ) {
1201        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1202        return;
1203    }
1204    process_media_player_call( env, thiz, mp->attachAuxEffect(effectId), NULL, NULL );
1205}
1206
1207/////////////////////////////////////////////////////////////////////////////////////
1208// Modular DRM begin
1209
1210// TODO: investigate if these can be shared with their MediaDrm counterparts
1211static void throwDrmStateException(JNIEnv *env, const char *msg, status_t err)
1212{
1213    ALOGE("Illegal DRM state exception: %s (%d)", msg, err);
1214
1215    jobject exception = env->NewObject(gStateExceptionFields.classId,
1216            gStateExceptionFields.init, static_cast<int>(err),
1217            env->NewStringUTF(msg));
1218    env->Throw(static_cast<jthrowable>(exception));
1219}
1220
1221// TODO: investigate if these can be shared with their MediaDrm counterparts
1222static bool throwDrmExceptionAsNecessary(JNIEnv *env, status_t err, const char *msg = NULL)
1223{
1224    const char *drmMessage = "Unknown DRM Msg";
1225
1226    switch (err) {
1227    case ERROR_DRM_UNKNOWN:
1228        drmMessage = "General DRM error";
1229        break;
1230    case ERROR_DRM_NO_LICENSE:
1231        drmMessage = "No license";
1232        break;
1233    case ERROR_DRM_LICENSE_EXPIRED:
1234        drmMessage = "License expired";
1235        break;
1236    case ERROR_DRM_SESSION_NOT_OPENED:
1237        drmMessage = "Session not opened";
1238        break;
1239    case ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED:
1240        drmMessage = "Not initialized";
1241        break;
1242    case ERROR_DRM_DECRYPT:
1243        drmMessage = "Decrypt error";
1244        break;
1245    case ERROR_DRM_CANNOT_HANDLE:
1246        drmMessage = "Unsupported scheme or data format";
1247        break;
1248    case ERROR_DRM_TAMPER_DETECTED:
1249        drmMessage = "Invalid state";
1250        break;
1251    default:
1252        break;
1253    }
1254
1255    String8 vendorMessage;
1256    if (err >= ERROR_DRM_VENDOR_MIN && err <= ERROR_DRM_VENDOR_MAX) {
1257        vendorMessage = String8::format("DRM vendor-defined error: %d", err);
1258        drmMessage = vendorMessage.string();
1259    }
1260
1261    if (err == BAD_VALUE) {
1262        jniThrowException(env, "java/lang/IllegalArgumentException", msg);
1263        return true;
1264    } else if (err == ERROR_DRM_NOT_PROVISIONED) {
1265        jniThrowException(env, "android/media/NotProvisionedException", msg);
1266        return true;
1267    } else if (err == ERROR_DRM_RESOURCE_BUSY) {
1268        jniThrowException(env, "android/media/ResourceBusyException", msg);
1269        return true;
1270    } else if (err == ERROR_DRM_DEVICE_REVOKED) {
1271        jniThrowException(env, "android/media/DeniedByServerException", msg);
1272        return true;
1273    } else if (err == DEAD_OBJECT) {
1274        jniThrowException(env, "android/media/MediaDrmResetException",
1275                          "mediaserver died");
1276        return true;
1277    } else if (err != OK) {
1278        String8 errbuf;
1279        if (drmMessage != NULL) {
1280            if (msg == NULL) {
1281                msg = drmMessage;
1282            } else {
1283                errbuf = String8::format("%s: %s", msg, drmMessage);
1284                msg = errbuf.string();
1285            }
1286        }
1287        throwDrmStateException(env, msg, err);
1288        return true;
1289    }
1290    return false;
1291}
1292
1293static Vector<uint8_t> JByteArrayToVector(JNIEnv *env, jbyteArray const &byteArray)
1294{
1295    Vector<uint8_t> vector;
1296    size_t length = env->GetArrayLength(byteArray);
1297    vector.insertAt((size_t)0, length);
1298    env->GetByteArrayRegion(byteArray, 0, length, (jbyte *)vector.editArray());
1299    return vector;
1300}
1301
1302static void android_media_MediaPlayer2_prepareDrm(JNIEnv *env, jobject thiz,
1303                    jbyteArray uuidObj, jbyteArray drmSessionIdObj)
1304{
1305    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1306    if (mp == NULL) {
1307        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1308        return;
1309    }
1310
1311    if (uuidObj == NULL) {
1312        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
1313        return;
1314    }
1315
1316    Vector<uint8_t> uuid = JByteArrayToVector(env, uuidObj);
1317
1318    if (uuid.size() != 16) {
1319        jniThrowException(
1320                          env,
1321                          "java/lang/IllegalArgumentException",
1322                          "invalid UUID size, expected 16 bytes");
1323        return;
1324    }
1325
1326    Vector<uint8_t> drmSessionId = JByteArrayToVector(env, drmSessionIdObj);
1327
1328    if (drmSessionId.size() == 0) {
1329        jniThrowException(
1330                          env,
1331                          "java/lang/IllegalArgumentException",
1332                          "empty drmSessionId");
1333        return;
1334    }
1335
1336    status_t err = mp->prepareDrm(uuid.array(), drmSessionId);
1337    if (err != OK) {
1338        if (err == INVALID_OPERATION) {
1339            jniThrowException(
1340                              env,
1341                              "java/lang/IllegalStateException",
1342                              "The player must be in prepared state.");
1343        } else if (err == ERROR_DRM_CANNOT_HANDLE) {
1344            jniThrowException(
1345                              env,
1346                              "android/media/UnsupportedSchemeException",
1347                              "Failed to instantiate drm object.");
1348        } else {
1349            throwDrmExceptionAsNecessary(env, err, "Failed to prepare DRM scheme");
1350        }
1351    }
1352}
1353
1354static void android_media_MediaPlayer2_releaseDrm(JNIEnv *env, jobject thiz)
1355{
1356    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1357    if (mp == NULL ) {
1358        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1359        return;
1360    }
1361
1362    status_t err = mp->releaseDrm();
1363    if (err != OK) {
1364        if (err == INVALID_OPERATION) {
1365            jniThrowException(
1366                              env,
1367                              "java/lang/IllegalStateException",
1368                              "Can not release DRM in an active player state.");
1369        }
1370    }
1371}
1372// Modular DRM end
1373// ----------------------------------------------------------------------------
1374
1375/////////////////////////////////////////////////////////////////////////////////////
1376// AudioRouting begin
1377static jboolean android_media_MediaPlayer2_setOutputDevice(JNIEnv *env, jobject thiz, jint device_id)
1378{
1379    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1380    if (mp == NULL) {
1381        return false;
1382    }
1383    return mp->setOutputDevice(device_id) == NO_ERROR;
1384}
1385
1386static jint android_media_MediaPlayer2_getRoutedDeviceId(JNIEnv *env, jobject thiz)
1387{
1388    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1389    if (mp == NULL) {
1390        return AUDIO_PORT_HANDLE_NONE;
1391    }
1392    return mp->getRoutedDeviceId();
1393}
1394
1395static void android_media_MediaPlayer2_enableDeviceCallback(
1396        JNIEnv* env, jobject thiz, jboolean enabled)
1397{
1398    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
1399    if (mp == NULL) {
1400        return;
1401    }
1402
1403    status_t status = mp->enableAudioDeviceCallback(enabled);
1404    if (status != NO_ERROR) {
1405        jniThrowException(env, "java/lang/IllegalStateException", NULL);
1406        ALOGE("enable device callback failed: %d", status);
1407    }
1408}
1409
1410// AudioRouting end
1411// ----------------------------------------------------------------------------
1412
1413/////////////////////////////////////////////////////////////////////////////////////
1414// AudioTrack.StreamEventCallback begin
1415static void android_media_MediaPlayer2_native_on_tear_down(JNIEnv *env __unused,
1416        jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
1417{
1418    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
1419    if (callback != NULL) {
1420        callback(JAudioTrack::EVENT_NEW_IAUDIOTRACK, (void *) userDataPtr, NULL);
1421    }
1422}
1423
1424static void android_media_MediaPlayer2_native_on_stream_presentation_end(JNIEnv *env __unused,
1425        jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
1426{
1427    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
1428    if (callback != NULL) {
1429        callback(JAudioTrack::EVENT_STREAM_END, (void *) userDataPtr, NULL);
1430    }
1431}
1432
1433static void android_media_MediaPlayer2_native_on_stream_data_request(JNIEnv *env __unused,
1434        jobject thiz __unused, jlong jAudioTrackPtr, jlong callbackPtr, jlong userDataPtr)
1435{
1436    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
1437    JAudioTrack* track = (JAudioTrack *) jAudioTrackPtr;
1438    if (callback != NULL && track != NULL) {
1439        JAudioTrack::Buffer* buffer = new JAudioTrack::Buffer();
1440
1441        size_t bufferSizeInFrames = track->frameCount();
1442        audio_format_t format = track->format();
1443
1444        size_t bufferSizeInBytes;
1445        if (audio_has_proportional_frames(format)) {
1446            bufferSizeInBytes =
1447                    bufferSizeInFrames * audio_bytes_per_sample(format) * track->channelCount();
1448        } else {
1449            // See Javadoc of AudioTrack::getBufferSizeInFrames().
1450            bufferSizeInBytes = bufferSizeInFrames;
1451        }
1452
1453        uint8_t* byteBuffer = new uint8_t[bufferSizeInBytes];
1454        buffer->mSize = bufferSizeInBytes;
1455        buffer->mData = (void *) byteBuffer;
1456
1457        callback(JAudioTrack::EVENT_MORE_DATA, (void *) userDataPtr, buffer);
1458
1459        if (buffer->mSize > 0 && buffer->mData == byteBuffer) {
1460            track->write(buffer->mData, buffer->mSize, true /* Blocking */);
1461        }
1462
1463        delete[] byteBuffer;
1464        delete buffer;
1465    }
1466}
1467
1468
1469// AudioTrack.StreamEventCallback end
1470// ----------------------------------------------------------------------------
1471
1472static const JNINativeMethod gMethods[] = {
1473    {
1474        "nativeHandleDataSourceUrl",
1475        "(ZJLandroid/media/Media2HTTPService;Ljava/lang/String;[Ljava/lang/String;"
1476        "[Ljava/lang/String;)V",
1477        (void *)android_media_MediaPlayer2_handleDataSourceUrl
1478    },
1479    {
1480        "nativeHandleDataSourceFD",
1481        "(ZJLjava/io/FileDescriptor;JJ)V",
1482        (void *)android_media_MediaPlayer2_handleDataSourceFD
1483    },
1484    {
1485        "nativeHandleDataSourceCallback",
1486        "(ZJLandroid/media/Media2DataSource;)V",
1487        (void *)android_media_MediaPlayer2_handleDataSourceCallback
1488    },
1489    {"nativePlayNextDataSource", "(J)V",                        (void *)android_media_MediaPlayer2_playNextDataSource},
1490    {"_setVideoSurface",    "(Landroid/view/Surface;)V",        (void *)android_media_MediaPlayer2_setVideoSurface},
1491    {"getBufferingParams", "()Landroid/media/BufferingParams;", (void *)android_media_MediaPlayer2_getBufferingParams},
1492    {"setBufferingParams", "(Landroid/media/BufferingParams;)V", (void *)android_media_MediaPlayer2_setBufferingParams},
1493    {"_prepare",            "()V",                              (void *)android_media_MediaPlayer2_prepare},
1494    {"_start",              "()V",                              (void *)android_media_MediaPlayer2_start},
1495    {"_stop",               "()V",                              (void *)android_media_MediaPlayer2_stop},
1496    {"native_getMediaPlayer2State", "()I",                      (void *)android_media_MediaPlayer2_getMediaPlayer2State},
1497    {"getVideoWidth",       "()I",                              (void *)android_media_MediaPlayer2_getVideoWidth},
1498    {"getVideoHeight",      "()I",                              (void *)android_media_MediaPlayer2_getVideoHeight},
1499    {"native_getMetrics",   "()Landroid/os/PersistableBundle;", (void *)android_media_MediaPlayer2_native_getMetrics},
1500    {"setPlaybackParams", "(Landroid/media/PlaybackParams;)V", (void *)android_media_MediaPlayer2_setPlaybackParams},
1501    {"getPlaybackParams", "()Landroid/media/PlaybackParams;", (void *)android_media_MediaPlayer2_getPlaybackParams},
1502    {"setSyncParams",     "(Landroid/media/SyncParams;)V",  (void *)android_media_MediaPlayer2_setSyncParams},
1503    {"getSyncParams",     "()Landroid/media/SyncParams;",   (void *)android_media_MediaPlayer2_getSyncParams},
1504    {"_seekTo",             "(JI)V",                            (void *)android_media_MediaPlayer2_seekTo},
1505    {"_notifyAt",           "(J)V",                             (void *)android_media_MediaPlayer2_notifyAt},
1506    {"_pause",              "()V",                              (void *)android_media_MediaPlayer2_pause},
1507    {"isPlaying",           "()Z",                              (void *)android_media_MediaPlayer2_isPlaying},
1508    {"getCurrentPosition",  "()J",                              (void *)android_media_MediaPlayer2_getCurrentPosition},
1509    {"getDuration",         "()J",                              (void *)android_media_MediaPlayer2_getDuration},
1510    {"_release",            "()V",                              (void *)android_media_MediaPlayer2_release},
1511    {"_reset",              "()V",                              (void *)android_media_MediaPlayer2_reset},
1512    {"_getAudioStreamType", "()I",                              (void *)android_media_MediaPlayer2_getAudioStreamType},
1513    {"setParameter",        "(ILandroid/os/Parcel;)Z",          (void *)android_media_MediaPlayer2_setParameter},
1514    {"getParameter",        "(I)Landroid/os/Parcel;",           (void *)android_media_MediaPlayer2_getParameter},
1515    {"setLooping",          "(Z)V",                             (void *)android_media_MediaPlayer2_setLooping},
1516    {"isLooping",           "()Z",                              (void *)android_media_MediaPlayer2_isLooping},
1517    {"_setVolume",          "(FF)V",                            (void *)android_media_MediaPlayer2_setVolume},
1518    {"native_invoke",       "(Landroid/os/Parcel;Landroid/os/Parcel;)I",(void *)android_media_MediaPlayer2_invoke},
1519    {"native_setMetadataFilter", "(Landroid/os/Parcel;)I",      (void *)android_media_MediaPlayer2_setMetadataFilter},
1520    {"native_getMetadata", "(ZZLandroid/os/Parcel;)Z",          (void *)android_media_MediaPlayer2_getMetadata},
1521    {"native_init",         "()V",                              (void *)android_media_MediaPlayer2_native_init},
1522    {"native_setup",        "(Ljava/lang/Object;)V",            (void *)android_media_MediaPlayer2_native_setup},
1523    {"native_finalize",     "()V",                              (void *)android_media_MediaPlayer2_native_finalize},
1524    {"getAudioSessionId",   "()I",                              (void *)android_media_MediaPlayer2_get_audio_session_id},
1525    {"setAudioSessionId",   "(I)V",                             (void *)android_media_MediaPlayer2_set_audio_session_id},
1526    {"_setAuxEffectSendLevel", "(F)V",                          (void *)android_media_MediaPlayer2_setAuxEffectSendLevel},
1527    {"attachAuxEffect",     "(I)V",                             (void *)android_media_MediaPlayer2_attachAuxEffect},
1528    // Modular DRM
1529    { "_prepareDrm", "([B[B)V",                                 (void *)android_media_MediaPlayer2_prepareDrm },
1530    { "_releaseDrm", "()V",                                     (void *)android_media_MediaPlayer2_releaseDrm },
1531
1532    // AudioRouting
1533    {"native_setOutputDevice", "(I)Z",                          (void *)android_media_MediaPlayer2_setOutputDevice},
1534    {"native_getRoutedDeviceId", "()I",                         (void *)android_media_MediaPlayer2_getRoutedDeviceId},
1535    {"native_enableDeviceCallback", "(Z)V",                     (void *)android_media_MediaPlayer2_enableDeviceCallback},
1536
1537    // StreamEventCallback for JAudioTrack
1538    {"native_stream_event_onTearDown",                "(JJ)V",  (void *)android_media_MediaPlayer2_native_on_tear_down},
1539    {"native_stream_event_onStreamPresentationEnd",   "(JJ)V",  (void *)android_media_MediaPlayer2_native_on_stream_presentation_end},
1540    {"native_stream_event_onStreamDataRequest",       "(JJJ)V", (void *)android_media_MediaPlayer2_native_on_stream_data_request},
1541};
1542
1543// This function only registers the native methods
1544static int register_android_media_MediaPlayer2Impl(JNIEnv *env)
1545{
1546    return AndroidRuntime::registerNativeMethods(env,
1547                "android/media/MediaPlayer2Impl", gMethods, NELEM(gMethods));
1548}
1549
1550jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
1551{
1552    JNIEnv* env = NULL;
1553    jint result = -1;
1554
1555    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
1556        ALOGE("ERROR: GetEnv failed\n");
1557        goto bail;
1558    }
1559    assert(env != NULL);
1560
1561    if (register_android_media_MediaPlayer2Impl(env) < 0) {
1562        ALOGE("ERROR: MediaPlayer2 native registration failed\n");
1563        goto bail;
1564    }
1565
1566    /* success -- return valid version number */
1567    result = JNI_VERSION_1_4;
1568
1569bail:
1570    return result;
1571}
1572
1573// KTHXBYE
1574