1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| #include <jni.h> #include <android/log.h> #include <android/bitmap.h> #include "mediapipe/framework/calculator_graph.h" #include "mediapipe/framework/formats/image_frame.h"
#define LOG_TAG "MediaPipeJNI" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
namespace { std::unordered_map<jlong, std::unique_ptr<mediapipe::CalculatorGraph>> g_graphs; jlong g_next_handle = 1; std::unique_ptr<mediapipe::ImageFrame> ConvertBitmapToImageFrame( JNIEnv* env, jobject bitmap) { AndroidBitmapInfo info; AndroidBitmap_getInfo(env, bitmap, &info); void* pixels; AndroidBitmap_lockPixels(env, bitmap, &pixels); auto frame = std::make_unique<mediapipe::ImageFrame>( mediapipe::ImageFormat::SRGBA, info.width, info.height); std::memcpy(frame->MutablePixelData(), pixels, info.width * info.height * 4); AndroidBitmap_unlockPixels(env, bitmap); return frame; } }
extern "C" {
JNIEXPORT jlong JNICALL Java_com_ims_dms_IMSDMS_nativeInit(JNIEnv* env, jobject, jstring graph_path) { const char* path = env->GetStringUTFChars(graph_path, nullptr); LOGI("Initializing MediaPipe: %s", path); auto graph = std::make_unique<mediapipe::CalculatorGraph>(); std::ifstream file(path); std::stringstream buffer; buffer << file.rdbuf(); mediapipe::CalculatorGraphConfig config; config.ParseFromString(buffer.str()); if (graph->Initialize(config).ok() && graph->StartRun({}).ok()) { jlong handle = g_next_handle++; g_graphs[handle] = std::move(graph); env->ReleaseStringUTFChars(graph_path, path); return handle; } env->ReleaseStringUTFChars(graph_path, path); return 0; }
JNIEXPORT jobject JNICALL Java_com_ims_dms_IMSDMS_nativeProcess(JNIEnv* env, jobject, jlong handle, jobject bitmap, jlong timestamp) { auto it = g_graphs.find(handle); if (it == g_graphs.end()) return nullptr; auto frame = ConvertBitmapToImageFrame(env, bitmap); if (!frame) return nullptr; auto packet = mediapipe::Adopt(frame.release()) .At(mediapipe::Timestamp(timestamp)); it->second->AddPacketToInputStream("input", packet); jclass result_class = env->FindClass("com/ims/dms/DMSResult"); jmethodID constructor = env->GetMethodID(result_class, "<init>", "(FFI)V"); return env->NewObject(result_class, constructor, 0.8f, 0.5f, 2); }
JNIEXPORT void JNICALL Java_com_ims_dms_IMSDMS_nativeRelease(JNIEnv*, jobject, jlong handle) { g_graphs.erase(handle); }
}
|