kmpmpv_bridge.cpp
vendor/kmp-mpv/android-bridge/src/main/cpp/kmpmpv_bridge.cpp
1#include <jni.h>23#include <dlfcn.h>45#include <cstdint>6#include <cstring>7#include <memory>8#include <string>9#include <utility>10#include <vector>1112#include "mpv_abi.h"1314namespace {1516constexpr int MPV_EVENT_LOG_MESSAGE = 2;17constexpr int MPV_EVENT_END_FILE = 7;18constexpr int MPV_EVENT_CLIENT_MESSAGE = 16;19constexpr int MPV_EVENT_PROPERTY_CHANGE = 22;20constexpr int MPV_ERROR_UNINITIALIZED = -3;21constexpr int MPV_ERROR_INVALID_PARAMETER = -4;2223struct Api {24 mpv_handle *(*create)();25 int (*set_java_vm)(void *, void *);26 int (*initialize)(mpv_handle *);27 int (*set_option_string)(mpv_handle *, const char *, const char *);28 int (*set_option)(mpv_handle *, const char *, int, void *);29 int (*command)(mpv_handle *, const char **);30 int (*get_property)(mpv_handle *, const char *, int, void *);31 int (*set_property)(mpv_handle *, const char *, int, void *);32 int (*set_property_string)(mpv_handle *, const char *, const char *);33 int (*observe_property)(mpv_handle *, std::uint64_t, const char *, int);34 int (*unobserve_property)(mpv_handle *, std::uint64_t);35 int (*request_log_messages)(mpv_handle *, const char *);36 mpv_event *(*wait_event)(mpv_handle *, double);37 const char *(*error_string)(int);38 void (*free_data)(void *);39 void (*wakeup)(mpv_handle *);40 void (*terminate_destroy)(mpv_handle *);41};4243struct Context {44 void *library = nullptr;45 Api api{};46 mpv_handle *handle = nullptr;47 jobject surface = nullptr;48 int last_result = 0;49};5051thread_local std::string last_error;5253template <typename T>54bool resolve(void *library, const char *name, T *target) {55 *target = reinterpret_cast<T>(dlsym(library, name));56 if (*target) return true;57 last_error = "Missing libmpv symbol: ";58 last_error += name;59 return false;60}6162bool resolve_api(void *library, Api *api) {63 return resolve(library, "av_jni_set_java_vm", &api->set_java_vm) &&64 resolve(library, "mpv_create", &api->create) &&65 resolve(library, "mpv_initialize", &api->initialize) &&66 resolve(library, "mpv_set_option_string", &api->set_option_string) &&67 resolve(library, "mpv_set_option", &api->set_option) &&68 resolve(library, "mpv_command", &api->command) &&69 resolve(library, "mpv_get_property", &api->get_property) &&70 resolve(library, "mpv_set_property", &api->set_property) &&71 resolve(library, "mpv_set_property_string", &api->set_property_string) &&72 resolve(library, "mpv_observe_property", &api->observe_property) &&73 resolve(library, "mpv_unobserve_property", &api->unobserve_property) &&74 resolve(library, "mpv_request_log_messages", &api->request_log_messages) &&75 resolve(library, "mpv_wait_event", &api->wait_event) &&76 resolve(library, "mpv_error_string", &api->error_string) &&77 resolve(library, "mpv_free", &api->free_data) &&78 resolve(library, "mpv_wakeup", &api->wakeup) &&79 resolve(library, "mpv_terminate_destroy", &api->terminate_destroy);80}8182Context *from_handle(jlong value) {83 return reinterpret_cast<Context *>(static_cast<std::intptr_t>(value));84}8586jlong to_handle(Context *context) {87 return static_cast<jlong>(reinterpret_cast<std::intptr_t>(context));88}8990class UtfChars {91public:92 UtfChars(JNIEnv *env, jstring value) : env_(env), value_(value) {93 chars_ = value ? env->GetStringUTFChars(value, nullptr) : nullptr;94 }9596 ~UtfChars() {97 if (chars_) env_->ReleaseStringUTFChars(value_, chars_);98 }99100 const char *get() const { return chars_; }101102private:103 JNIEnv *env_;104 jstring value_;105 const char *chars_ = nullptr;106};107108jstring new_utf8_string(JNIEnv *env, const char *value) {109 if (!value) return nullptr;110 const jsize length = static_cast<jsize>(std::strlen(value));111 jbyteArray bytes = env->NewByteArray(length);112 if (!bytes) return nullptr;113 env->SetByteArrayRegion(bytes, 0, length, reinterpret_cast<const jbyte *>(value));114 jclass string_type = env->FindClass("java/lang/String");115 jstring charset = env->NewStringUTF("UTF-8");116 jmethodID constructor = env->GetMethodID(string_type, "<init>", "([BLjava/lang/String;)V");117 jstring result = static_cast<jstring>(env->NewObject(string_type, constructor, bytes, charset));118 env->DeleteLocalRef(charset);119 env->DeleteLocalRef(string_type);120 env->DeleteLocalRef(bytes);121 return result;122}123124jobject box_long(JNIEnv *env, std::int64_t value) {125 jclass type = env->FindClass("java/lang/Long");126 jmethodID method = env->GetStaticMethodID(type, "valueOf", "(J)Ljava/lang/Long;");127 return env->CallStaticObjectMethod(type, method, static_cast<jlong>(value));128}129130jobject box_boolean(JNIEnv *env, bool value) {131 jclass type = env->FindClass("java/lang/Boolean");132 jmethodID method = env->GetStaticMethodID(type, "valueOf", "(Z)Ljava/lang/Boolean;");133 return env->CallStaticObjectMethod(type, method, static_cast<jboolean>(value));134}135136jobject box_double(JNIEnv *env, double value) {137 jclass type = env->FindClass("java/lang/Double");138 jmethodID method = env->GetStaticMethodID(type, "valueOf", "(D)Ljava/lang/Double;");139 return env->CallStaticObjectMethod(type, method, static_cast<jdouble>(value));140}141142jobject property_value(JNIEnv *env, int format, void *data) {143 if (!data) return nullptr;144 switch (format) {145 case MPV_FORMAT_STRING:146 case MPV_FORMAT_OSD_STRING:147 return new_utf8_string(env, static_cast<const char *>(data));148 case MPV_FORMAT_FLAG:149 return box_boolean(env, *static_cast<int *>(data) != 0);150 case MPV_FORMAT_INT64:151 return box_long(env, *static_cast<std::int64_t *>(data));152 case MPV_FORMAT_DOUBLE:153 return box_double(env, *static_cast<double *>(data));154 default:155 return nullptr;156 }157}158159jobject read_boxed_value(JNIEnv *env, jobject value, int format, std::int64_t *integer, double *decimal) {160 if (!value) return nullptr;161 switch (format) {162 case MPV_FORMAT_FLAG: {163 jclass type = env->FindClass("java/lang/Boolean");164 jmethodID method = env->GetMethodID(type, "booleanValue", "()Z");165 *integer = env->CallBooleanMethod(value, method) ? 1 : 0;166 return value;167 }168 case MPV_FORMAT_INT64: {169 jclass type = env->FindClass("java/lang/Number");170 jmethodID method = env->GetMethodID(type, "longValue", "()J");171 *integer = env->CallLongMethod(value, method);172 return value;173 }174 case MPV_FORMAT_DOUBLE: {175 jclass type = env->FindClass("java/lang/Number");176 jmethodID method = env->GetMethodID(type, "doubleValue", "()D");177 *decimal = env->CallDoubleMethod(value, method);178 return value;179 }180 default:181 return nullptr;182 }183}184185jobjectArray make_string_array(JNIEnv *env, const mpv_event_client_message *message) {186 if (!message || message->num_args <= 0 || !message->args) return nullptr;187 jclass string_type = env->FindClass("java/lang/String");188 jobjectArray result = env->NewObjectArray(message->num_args, string_type, nullptr);189 for (int i = 0; i < message->num_args; ++i) {190 jstring item = new_utf8_string(env, message->args[i]);191 env->SetObjectArrayElement(result, i, item);192 if (item) env->DeleteLocalRef(item);193 }194 return result;195}196197jobject make_event(JNIEnv *env, const mpv_event *event) {198 const mpv_event_property *property = nullptr;199 const mpv_event_log_message *log = nullptr;200 const mpv_event_end_file *end_file = nullptr;201 const mpv_event_client_message *client_message = nullptr;202203 if (event->event_id == MPV_EVENT_PROPERTY_CHANGE)204 property = static_cast<const mpv_event_property *>(event->data);205 if (event->event_id == MPV_EVENT_LOG_MESSAGE)206 log = static_cast<const mpv_event_log_message *>(event->data);207 if (event->event_id == MPV_EVENT_END_FILE)208 end_file = static_cast<const mpv_event_end_file *>(event->data);209 if (event->event_id == MPV_EVENT_CLIENT_MESSAGE)210 client_message = static_cast<const mpv_event_client_message *>(event->data);211212 jstring property_name = property ? new_utf8_string(env, property->name) : nullptr;213 jobject value = property ? property_value(env, property->format, property->data) : nullptr;214 jstring log_prefix = log ? new_utf8_string(env, log->prefix) : nullptr;215 jstring log_text = log ? new_utf8_string(env, log->text) : nullptr;216 jobjectArray arguments = make_string_array(env, client_message);217218 jclass type = env->FindClass("io/github/kmpmpv/bridge/MpvNativeEvent");219 jmethodID constructor = env->GetMethodID(220 type,221 "<init>",222 "(IIJLjava/lang/String;Ljava/lang/Object;Ljava/lang/String;ILjava/lang/String;II[Ljava/lang/String;)V");223 jobject result = env->NewObject(224 type,225 constructor,226 event->event_id,227 event->error,228 static_cast<jlong>(event->reply_userdata),229 property_name,230 value,231 log_prefix,232 log ? log->log_level : 0,233 log_text,234 end_file ? end_file->reason : 0,235 end_file ? end_file->error : 0,236 arguments);237238 if (property_name) env->DeleteLocalRef(property_name);239 if (value) env->DeleteLocalRef(value);240 if (log_prefix) env->DeleteLocalRef(log_prefix);241 if (log_text) env->DeleteLocalRef(log_text);242 if (arguments) env->DeleteLocalRef(arguments);243 return result;244}245246} // namespace247248extern "C" JNIEXPORT jlong JNICALL249Java_io_github_kmpmpv_bridge_MpvNative_create(JNIEnv *env, jclass, jstring library_path) {250 UtfChars requested_path(env, library_path);251 const char *path = requested_path.get() ? requested_path.get() : "libmpv.so";252 void *library = dlopen(path, RTLD_NOW | RTLD_LOCAL);253 if (!library) {254 const char *error = dlerror();255 last_error = error ? error : "dlopen(libmpv) failed";256 return 0;257 }258259 std::unique_ptr<Context> context(new Context());260 context->library = library;261 if (!resolve_api(library, &context->api)) {262 dlclose(library);263 return 0;264 }265 JavaVM *java_vm = nullptr;266 if (env->GetJavaVM(&java_vm) != JNI_OK || !java_vm ||267 context->api.set_java_vm(java_vm, nullptr) < 0) {268 last_error = "Failed to register the Android Java VM with libmpv";269 dlclose(library);270 return 0;271 }272 context->handle = context->api.create();273 if (!context->handle) {274 last_error = "mpv_create returned null";275 dlclose(library);276 return 0;277 }278 return to_handle(context.release());279}280281extern "C" JNIEXPORT jstring JNICALL282Java_io_github_kmpmpv_bridge_MpvNative_lastError(JNIEnv *env, jclass) {283 return new_utf8_string(env, last_error.c_str());284}285286extern "C" JNIEXPORT jint JNICALL287Java_io_github_kmpmpv_bridge_MpvNative_initialize(JNIEnv *, jclass, jlong value) {288 Context *context = from_handle(value);289 if (!context) return MPV_ERROR_UNINITIALIZED;290 return context->api.initialize(context->handle);291}292293extern "C" JNIEXPORT jint JNICALL294Java_io_github_kmpmpv_bridge_MpvNative_setOptionString(295 JNIEnv *env, jclass, jlong value, jstring name, jstring option_value) {296 Context *context = from_handle(value);297 if (!context) return MPV_ERROR_UNINITIALIZED;298 UtfChars native_name(env, name);299 UtfChars native_value(env, option_value);300 return context->api.set_option_string(context->handle, native_name.get(), native_value.get());301}302303extern "C" JNIEXPORT jint JNICALL304Java_io_github_kmpmpv_bridge_MpvNative_command(305 JNIEnv *env, jclass, jlong value, jobjectArray arguments) {306 Context *context = from_handle(value);307 if (!context) return MPV_ERROR_UNINITIALIZED;308 const jsize count = env->GetArrayLength(arguments);309 std::vector<std::string> strings;310 strings.reserve(static_cast<std::size_t>(count));311 for (jsize i = 0; i < count; ++i) {312 auto item = static_cast<jstring>(env->GetObjectArrayElement(arguments, i));313 {314 UtfChars text(env, item);315 strings.emplace_back(text.get() ? text.get() : "");316 }317 env->DeleteLocalRef(item);318 }319 std::vector<const char *> pointers;320 pointers.reserve(strings.size() + 1);321 for (const std::string &item : strings) pointers.push_back(item.c_str());322 pointers.push_back(nullptr);323 return context->api.command(context->handle, pointers.data());324}325326extern "C" JNIEXPORT jobject JNICALL327Java_io_github_kmpmpv_bridge_MpvNative_getProperty(328 JNIEnv *env, jclass, jlong value, jstring name, jint format) {329 Context *context = from_handle(value);330 if (!context) return nullptr;331 UtfChars native_name(env, name);332333 if (format == MPV_FORMAT_STRING || format == MPV_FORMAT_OSD_STRING) {334 char *result = nullptr;335 context->last_result = context->api.get_property(336 context->handle, native_name.get(), format, &result);337 if (context->last_result < 0 || !result) return nullptr;338 jstring text = new_utf8_string(env, result);339 context->api.free_data(result);340 return text;341 }342 if (format == MPV_FORMAT_FLAG) {343 int result = 0;344 context->last_result = context->api.get_property(345 context->handle, native_name.get(), format, &result);346 return context->last_result < 0 ? nullptr : box_boolean(env, result != 0);347 }348 if (format == MPV_FORMAT_INT64) {349 std::int64_t result = 0;350 context->last_result = context->api.get_property(351 context->handle, native_name.get(), format, &result);352 return context->last_result < 0 ? nullptr : box_long(env, result);353 }354 if (format == MPV_FORMAT_DOUBLE) {355 double result = 0;356 context->last_result = context->api.get_property(357 context->handle, native_name.get(), format, &result);358 return context->last_result < 0 ? nullptr : box_double(env, result);359 }360 context->last_result = MPV_ERROR_INVALID_PARAMETER;361 return nullptr;362}363364extern "C" JNIEXPORT jint JNICALL365Java_io_github_kmpmpv_bridge_MpvNative_lastOperationResult(366 JNIEnv *, jclass, jlong value) {367 Context *context = from_handle(value);368 return context ? context->last_result : MPV_ERROR_UNINITIALIZED;369}370371extern "C" JNIEXPORT jint JNICALL372Java_io_github_kmpmpv_bridge_MpvNative_setProperty(373 JNIEnv *env, jclass, jlong value, jstring name, jint format, jobject property_value_object) {374 Context *context = from_handle(value);375 if (!context) return MPV_ERROR_UNINITIALIZED;376 UtfChars native_name(env, name);377 if (format == MPV_FORMAT_STRING || format == MPV_FORMAT_OSD_STRING) {378 UtfChars text(env, static_cast<jstring>(property_value_object));379 return context->api.set_property_string(context->handle, native_name.get(), text.get());380 }381 std::int64_t integer = 0;382 double decimal = 0;383 if (!read_boxed_value(env, property_value_object, format, &integer, &decimal))384 return MPV_ERROR_INVALID_PARAMETER;385 if (format == MPV_FORMAT_FLAG) {386 int flag = integer != 0;387 return context->api.set_property(context->handle, native_name.get(), format, &flag);388 }389 if (format == MPV_FORMAT_INT64)390 return context->api.set_property(context->handle, native_name.get(), format, &integer);391 if (format == MPV_FORMAT_DOUBLE)392 return context->api.set_property(context->handle, native_name.get(), format, &decimal);393 return MPV_ERROR_INVALID_PARAMETER;394}395396extern "C" JNIEXPORT jint JNICALL397Java_io_github_kmpmpv_bridge_MpvNative_observeProperty(398 JNIEnv *env, jclass, jlong value, jlong id, jstring name, jint format) {399 Context *context = from_handle(value);400 if (!context) return MPV_ERROR_UNINITIALIZED;401 UtfChars native_name(env, name);402 return context->api.observe_property(context->handle, id, native_name.get(), format);403}404405extern "C" JNIEXPORT jint JNICALL406Java_io_github_kmpmpv_bridge_MpvNative_unobserveProperty(407 JNIEnv *, jclass, jlong value, jlong id) {408 Context *context = from_handle(value);409 return context ? context->api.unobserve_property(context->handle, id) : MPV_ERROR_UNINITIALIZED;410}411412extern "C" JNIEXPORT jint JNICALL413Java_io_github_kmpmpv_bridge_MpvNative_requestLogMessages(414 JNIEnv *env, jclass, jlong value, jstring level) {415 Context *context = from_handle(value);416 if (!context) return MPV_ERROR_UNINITIALIZED;417 UtfChars native_level(env, level);418 return context->api.request_log_messages(context->handle, native_level.get());419}420421extern "C" JNIEXPORT jobject JNICALL422Java_io_github_kmpmpv_bridge_MpvNative_waitEvent(423 JNIEnv *env, jclass, jlong value, jdouble timeout_seconds) {424 Context *context = from_handle(value);425 if (!context) return nullptr;426 mpv_event *event = context->api.wait_event(context->handle, timeout_seconds);427 return event ? make_event(env, event) : nullptr;428}429430extern "C" JNIEXPORT jstring JNICALL431Java_io_github_kmpmpv_bridge_MpvNative_errorString(432 JNIEnv *env, jclass, jlong value, jint error_code) {433 Context *context = from_handle(value);434 const char *message = context ? context->api.error_string(error_code) : "mpv client is not initialized";435 return new_utf8_string(env, message ? message : "unknown mpv error");436}437438extern "C" JNIEXPORT jint JNICALL439Java_io_github_kmpmpv_bridge_MpvNative_attachSurface(440 JNIEnv *env, jclass, jlong value, jobject surface) {441 Context *context = from_handle(value);442 if (!context) return MPV_ERROR_UNINITIALIZED;443 jobject replacement = env->NewGlobalRef(surface);444 if (!replacement) return MPV_ERROR_INVALID_PARAMETER;445 std::int64_t wid = reinterpret_cast<std::intptr_t>(replacement);446 int result = context->api.set_option(context->handle, "wid", MPV_FORMAT_INT64, &wid);447 if (result < 0) {448 env->DeleteGlobalRef(replacement);449 return result;450 }451 if (context->surface) env->DeleteGlobalRef(context->surface);452 context->surface = replacement;453 return result;454}455456extern "C" JNIEXPORT jint JNICALL457Java_io_github_kmpmpv_bridge_MpvNative_detachSurface(458 JNIEnv *env, jclass, jlong value) {459 Context *context = from_handle(value);460 if (!context) return MPV_ERROR_UNINITIALIZED;461 std::int64_t wid = 0;462 int result = context->api.set_option(context->handle, "wid", MPV_FORMAT_INT64, &wid);463 if (result >= 0 && context->surface) {464 env->DeleteGlobalRef(context->surface);465 context->surface = nullptr;466 }467 return result;468}469470extern "C" JNIEXPORT void JNICALL471Java_io_github_kmpmpv_bridge_MpvNative_wakeup(JNIEnv *, jclass, jlong value) {472 Context *context = from_handle(value);473 if (context) context->api.wakeup(context->handle);474}475476extern "C" JNIEXPORT void JNICALL477Java_io_github_kmpmpv_bridge_MpvNative_destroy(JNIEnv *env, jclass, jlong value) {478 std::unique_ptr<Context> context(from_handle(value));479 if (!context) return;480 // mpv's video output can still use the Surface during termination.481 if (context->handle) context->api.terminate_destroy(context->handle);482 if (context->surface) env->DeleteGlobalRef(context->surface);483 if (context->library) dlclose(context->library);484}485