X-Git-Url: https://git.sesse.net/?a=blobdiff_plain;f=libavcodec%2Fffjni.c;h=13eabb00337b909e7d61a0bbba4854a207b55332;hb=4c121ad5466a0ac8670f7e5253891554fc230e08;hp=82ee5d32ae760fb924cd2223eb5afe565593f45a;hpb=cd52ec2337ae0d78c53ed32602a100a67b829fe4;p=ffmpeg diff --git a/libavcodec/ffjni.c b/libavcodec/ffjni.c index 82ee5d32ae7..13eabb00337 100644 --- a/libavcodec/ffjni.c +++ b/libavcodec/ffjni.c @@ -31,25 +31,42 @@ #include "jni.h" #include "ffjni.h" -static JavaVM *java_vm = NULL; +static JavaVM *java_vm; +static pthread_key_t current_env; +static pthread_once_t once = PTHREAD_ONCE_INIT; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; -JNIEnv *ff_jni_attach_env(int *attached, void *log_ctx) +static void jni_detach_env(void *data) +{ + if (java_vm) { + (*java_vm)->DetachCurrentThread(java_vm); + } +} + +static void jni_create_pthread_key(void) +{ + pthread_key_create(¤t_env, jni_detach_env); +} + +JNIEnv *ff_jni_get_env(void *log_ctx) { int ret = 0; JNIEnv *env = NULL; - *attached = 0; - pthread_mutex_lock(&lock); if (java_vm == NULL) { java_vm = av_jni_get_java_vm(log_ctx); } - pthread_mutex_unlock(&lock); if (!java_vm) { av_log(log_ctx, AV_LOG_ERROR, "No Java virtual machine has been registered\n"); - return NULL; + goto done; + } + + pthread_once(&once, jni_create_pthread_key); + + if ((env = pthread_getspecific(current_env)) != NULL) { + goto done; } ret = (*java_vm)->GetEnv(java_vm, (void **)&env, JNI_VERSION_1_6); @@ -59,7 +76,7 @@ JNIEnv *ff_jni_attach_env(int *attached, void *log_ctx) av_log(log_ctx, AV_LOG_ERROR, "Failed to attach the JNI environment to the current thread\n"); env = NULL; } else { - *attached = 1; + pthread_setspecific(current_env, env); } break; case JNI_OK: @@ -72,19 +89,11 @@ JNIEnv *ff_jni_attach_env(int *attached, void *log_ctx) break; } +done: + pthread_mutex_unlock(&lock); return env; } -int ff_jni_detach_env(void *log_ctx) -{ - if (java_vm == NULL) { - av_log(log_ctx, AV_LOG_ERROR, "No Java virtual machine has been registered\n"); - return AVERROR(EINVAL); - } - - return (*java_vm)->DetachCurrentThread(java_vm); -} - char *ff_jni_jstring_to_utf_chars(JNIEnv *env, jstring string, void *log_ctx) { char *ret = NULL;