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