From 31bd1607497049d9cc0e2590d0415730de0113e0 Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Sun, 26 Nov 2023 16:17:44 +0100 Subject: [PATCH] Hide the ugliness of JNI --- client/application.cpp | 115 +++++----------- client/application.h | 34 +---- client/jnipp.h | 278 +++++++++++++++++++++++++++++++++++++++ client/scenes/stream.cpp | 4 +- 4 files changed, 319 insertions(+), 112 deletions(-) create mode 100644 client/jnipp.h diff --git a/client/application.cpp b/client/application.cpp index c2d03894..af05fa46 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -42,30 +42,14 @@ #ifdef XR_USE_PLATFORM_ANDROID #include #include + +#include "jnipp.h" #endif using namespace std::chrono_literals; application * application::instance_ = nullptr; -#ifdef XR_USE_PLATFORM_ANDROID -jni_thread::jni_thread(application & app) : - vm(app.app_info.native_app->activity->vm) -{ - vm->AttachCurrentThread(&env, nullptr); -} - -jni_thread::jni_thread() : - jni_thread(application::instance()) -{ -} - -jni_thread::~jni_thread() -{ - vm->DetachCurrentThread(); -} -#endif - VkBool32 application::vulkan_debug_report_callback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, @@ -139,7 +123,7 @@ void application::initialize_vulkan() std::vector layers; spdlog::info("Available Vulkan layers:"); - bool validation_layer_found = false; + [[maybe_unused]] bool validation_layer_found = false; for (VkLayerProperties & i: vk::details::enumerate(vkEnumerateInstanceLayerProperties)) { spdlog::info(" {}", i.layerName); @@ -499,43 +483,24 @@ std::pair application::get_action(const std::string & re } application::application(application_info info) : - app_info(std::move(info)), jni(*this) + app_info(std::move(info)) { #ifdef XR_USE_PLATFORM_ANDROID // https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html - JNIEnv * Env = jni.get_JNIEnv(); - ANativeActivity * activity = app_info.native_app->activity; + setup_jni(); + jni::object<""> act(app_info.native_app->activity->clazz); - jmethodID jtmID; + jni::string lock_name("WiVRn"); - jclass jNativeClass = Env->GetObjectClass(activity->clazz); - jtmID = Env->GetMethodID(jNativeClass, "getApplication", "()Landroid/app/Application;"); - - jobject jNativeApplication = Env->CallObjectMethod(activity->clazz, jtmID); - jtmID = Env->GetMethodID(Env->GetObjectClass(jNativeApplication), "getApplicationContext", "()Landroid/content/Context;"); - - jobject jNativeContext = Env->CallObjectMethod(jNativeApplication, jtmID); - jfieldID jNativeWIFI_SERVICE_fid = Env->GetStaticFieldID(Env->GetObjectClass(jNativeContext), "WIFI_SERVICE", "Ljava/lang/String;"); - jstring jNativeSFID_jstr = (jstring)Env->GetStaticObjectField(Env->FindClass("android/content/Context"), jNativeWIFI_SERVICE_fid); - jstring wifiLockjStr = Env->NewStringUTF("WIVRn"); - - jtmID = Env->GetMethodID(Env->FindClass("android/content/Context"), "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); - jobject jSystemService = Env->CallObjectMethod(jNativeContext, jtmID, jNativeSFID_jstr); - - jclass jWMClass = Env->FindClass("android/net/wifi/WifiManager"); - jclass jWMMLClass = Env->FindClass("android/net/wifi/WifiManager$MulticastLock"); - jtmID = Env->GetMethodID(jWMClass, "createMulticastLock", "(Ljava/lang/String;)Landroid/net/wifi/WifiManager$MulticastLock;"); - jobject jMCObj = Env->CallObjectMethod(jSystemService, jtmID, wifiLockjStr); - - jtmID = Env->GetMethodID(jWMMLClass, "setReferenceCounted", "(Z)V"); - Env->CallVoidMethod(jMCObj, jtmID, 0); - - jtmID = Env->GetMethodID(jWMMLClass, "acquire", "()V"); - Env->CallVoidMethod(jMCObj, jtmID); - jtmID = Env->GetMethodID(jWMMLClass, "isHeld", "()Z"); - jboolean isheld = Env->CallBooleanMethod(jMCObj, jtmID); - if (isheld) + auto app = act.call>("getApplication"); + auto ctx = app.call>("getApplicationContext"); + auto wifi_service_id = ctx.klass().field("WIFI_SERVICE"); + auto system_service = ctx.call>("getSystemService", wifi_service_id); + auto lock = system_service.call>("createMulticastLock", lock_name); + lock.call("setReferenceCounted", jni::Bool(false)); + lock.call("acquire"); + if (lock.call("isHeld")) { spdlog::info("MulticastLock acquired"); } @@ -544,19 +509,10 @@ application::application(application_info info) : spdlog::info("MulticastLock is not acquired"); } - jclass jWMWLClass = Env->FindClass("android/net/wifi/WifiManager$WifiLock"); - jtmID = Env->GetMethodID(jWMClass, "createWifiLock", "(ILjava/lang/String;)Landroid/net/wifi/WifiManager$WifiLock;"); - // jobject jMCObj2 = Env->CallObjectMethod(jSystemService, jtmID, 4 /* WIFI_MODE_FULL_LOW_LATENCY */, wifiLockjStr); - jobject jMCObj2 = Env->CallObjectMethod(jSystemService, jtmID, 3 /* WIFI_MODE_FULL_HIGH_PERF */, wifiLockjStr); - - jtmID = Env->GetMethodID(jWMWLClass, "setReferenceCounted", "(Z)V"); - Env->CallVoidMethod(jMCObj2, jtmID, 0); - - jtmID = Env->GetMethodID(jWMWLClass, "acquire", "()V"); - Env->CallVoidMethod(jMCObj2, jtmID); - jtmID = Env->GetMethodID(jWMWLClass, "isHeld", "()Z"); - isheld = Env->CallBooleanMethod(jMCObj2, jtmID); - if (isheld) + auto wifi_lock = system_service.call>("createWifiLock", jni::Int(3) /*WIFI_MODE_FULL_HIGH_PERF*/, lock_name); + wifi_lock.call("setReferenceCounted", jni::Bool(false)); + wifi_lock.call("acquire"); + if (wifi_lock.call("isHeld")) { spdlog::info("WifiLock low latency acquired"); } @@ -565,26 +521,18 @@ application::application(application_info info) : spdlog::info("WifiLock low latency is not acquired"); } - Env->DeleteLocalRef(wifiLockjStr); - // Get the intent, to handle wivrn://uri - jtmID = Env->GetMethodID(jNativeClass, "getIntent", "()Landroid/content/Intent;"); - jobject intent = Env->CallObjectMethod(activity->clazz, jtmID); - - jtmID = Env->GetMethodID(Env->GetObjectClass(intent), "getDataString", "()Ljava/lang/String;"); - jstring dataString_jni = (jstring)Env->CallObjectMethod(intent, jtmID); - std::string dataString; - if (dataString_jni) + auto intent = act.call>("getIntent"); + std::string data_string; + if (auto data_string_jni = intent.call("getDataString")) { - const char * dataString_c = Env->GetStringUTFChars(dataString_jni, NULL); - dataString = dataString_c; - Env->ReleaseStringUTFChars(dataString_jni, dataString_c); + data_string = data_string_jni; } - spdlog::info("dataString = {}", dataString); - if (dataString.starts_with("wivrn://")) + spdlog::info("dataString = {}", data_string); + if (data_string.starts_with("wivrn://")) { - server_address = dataString.substr(strlen("wivrn://")); + server_address = data_string.substr(strlen("wivrn://")); } app_info.native_app->userData = this; @@ -643,12 +591,19 @@ application::application(application_info info) : } } +#ifdef XR_USE_PLATFORM_ANDROID +void application::setup_jni() +{ + jni::jni_thread::setup_thread(app_info.native_app->activity->vm); +} +#endif + void application::cleanup() { // The Vulkan device and instance are destroyed by the OpenXR runtime #ifdef XR_USE_PLATFORM_ANDROID - app_info.native_app->activity->vm->DetachCurrentThread(); + jni::jni_thread::detach(); #endif assert(instance_ == this); instance_ = nullptr; @@ -698,7 +653,7 @@ void application::loop() void application::run() { std::thread application_thread{[&]() { - jni_thread jni; + setup_jni(); while (!is_exit_requested()) { diff --git a/client/application.h b/client/application.h index 2076ee27..d58ee8d9 100644 --- a/client/application.h +++ b/client/application.h @@ -49,38 +49,9 @@ struct application_info #endif }; -class application; - -#ifdef XR_USE_PLATFORM_ANDROID -class jni_thread -{ - JNIEnv * env = nullptr; - JavaVM * vm = nullptr; - -public: - explicit jni_thread(application & app); - jni_thread(); - ~jni_thread(); - - JNIEnv * get_JNIEnv() - { - return env; - } -}; -#else -class [[maybe_unused]] jni_thread -{ -public: - explicit jni_thread(application & app) {} - jni_thread() = default; - ~jni_thread() = default; -}; -#endif - class application { friend class scene; - friend class jni_thread; application_info app_info; #ifdef XR_USE_PLATFORM_ANDROID @@ -108,8 +79,6 @@ class application static application * instance_; - jni_thread jni; - // OpenXR stuff xr::instance xr_instance; xr::system xr_system_id; @@ -306,6 +275,9 @@ public: application(const application &) = delete; ~application(); +#ifdef XR_USE_PLATFORM_ANDROID + void setup_jni(); +#endif static bool is_session_running() { diff --git a/client/jnipp.h b/client/jnipp.h new file mode 100644 index 00000000..4c40be48 --- /dev/null +++ b/client/jnipp.h @@ -0,0 +1,278 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2023 Guillaume Meunier + * Copyright (C) 2023 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include + +#include + +namespace jni +{ +class jni_thread +{ + JNIEnv * jni_env = nullptr; + JavaVM * vm = nullptr; + + jni_thread() = default; + ~jni_thread() + { + if (vm) + vm->DetachCurrentThread(); + } + + static jni_thread & instance() + { + thread_local jni_thread inst; + return inst; + } + +public: + static JNIEnv & env() + { + auto res = instance().jni_env; + assert(res); + return *res; + } + + static void setup_thread(JavaVM * vm) + { + auto & inst = instance(); + if (inst.vm) + return; + inst.vm = vm; + inst.vm->AttachCurrentThread(&inst.jni_env, nullptr); + } + + static void detach() + { + instance() = jni_thread(); + } +}; + +namespace details +{ + +struct deleter +{ + void operator()(jobject j) + { + jni_thread::env().DeleteLocalRef(j); + } +}; + +template +std::string build_type(Args &&... args) +{ + return (std::string() + ... + std::remove_cvref_t::type()); +} + +template +struct string_literal +{ + constexpr string_literal(const char (&str)[N]) + { + std::copy_n(str, N, value); + }; + char value[N]; +}; + +inline auto handle() +{ + return std::tuple<>(); +} + +template +auto handle(const T & t, Args &&... args) +{ + return std::tuple_cat(std::make_tuple(t.handle()), handle(std::forward(args)...)); +} +} // namespace details + +struct klass +{ + std::unique_ptr, details::deleter> self; + + operator jclass() + { + return self.get(); + } + + template + klass(T & instance) + { + auto & env = jni_thread::env(); + self.reset(env.GetObjectClass(instance)); + } + + template + T field(const std::string & name) + { + auto & env = jni_thread::env(); + jfieldID id = env.GetStaticFieldID(*this, name.c_str(), T::type().c_str()); + return T((env.*T::static_field)(*this, id)); + } +}; + +struct Void +{ + static std::string type() + { + return "V"; + } + constexpr static const auto call_method = &_JNIEnv::CallVoidMethod; +}; + +struct Bool +{ + static std::string type() + { + return "Z"; + } + constexpr static const auto call_method = &_JNIEnv::CallBooleanMethod; + + bool value; + + int handle() const + { + return value; + } + + operator bool() const + { + return value; + } +}; + +struct Int +{ + static std::string type() + { + return "I"; + } + + int value; + + int handle() const + { + return value; + } + + operator int() const + { + return value; + } +}; + +namespace details +{ +template +struct type_map +{ + using type = T; +}; + +template <> +struct type_map +{ + using type = jni::Void; +}; + +template +using type_map_t = type_map::type; +}; // namespace details + +template +struct object +{ + static std::string type() + { + return std::string("L") + Type.value + ";"; + } + std::unique_ptr, details::deleter> self; + + constexpr static const auto call_method = &_JNIEnv::CallObjectMethod; + + object(jobject o) + { + auto & env = jni_thread::env(); + if (o) + self.reset(env.NewLocalRef(o)); + } + + template + auto call(const char * method, Args &&... args) + { + using R1 = details::type_map_t; + auto & env = jni_thread::env(); + std::string signature = "(" + details::build_type(args...) + ")" + R1::type(); + auto method_id = env.GetMethodID(klass(), method, signature.c_str()); + auto handles = details::handle(std::forward(args)...); + return R(std::apply([&](auto &... t) { + return (env.*R1::call_method)(*this, method_id, t...); + }, + handles)); + } + + jobject handle() const + { + return *this; + } + + operator jobject() const + { + return self.get(); + } + + klass klass() + { + return *this; + } +}; + +using string_t = object<"java/lang/String">; + +struct string : public string_t +{ + using string_t::type; + constexpr static auto static_field = &_JNIEnv::GetStaticObjectField; + + operator jstring() + { + return (jstring)self.get(); + } + + string(const char * str) : + string_t(jni_thread::env().NewStringUTF(str)) {} + string(jobject j) : + string_t(j) {} + + operator std::string() + { + auto & env = jni_thread::env(); + const char * dataString_c = env.GetStringUTFChars(*this, NULL); + std::string res = dataString_c; + env.ReleaseStringUTFChars(*this, dataString_c); + return res; + } +}; +} // namespace jni diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 685e2077..e2710d7a 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -535,7 +535,9 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript void scenes::stream::video() { - jni_thread jni; +#ifdef XR_USE_PLATFORM_ANDROID + application::instance().setup_jni(); +#endif while (not exiting) {