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