paddle_mobile_jni.cpp 15.5 KB
Newer Older
W
wangliu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#ifdef ANDROID

17
#include "io/jni/paddle_mobile_jni.h"
D
dolphin8 已提交
18
#include <cmath>
19 20
#include <string>
#include <vector>
21 22 23 24
#include "common/log.h"
#include "framework/tensor.h"
#include "io/paddle_mobile.h"

25 26 27 28
#ifdef ENABLE_EXCEPTION
#include "common/enforce.h"
#endif

W
wangliu 已提交
29 30 31
#ifdef __cplusplus
extern "C" {
#endif
32

W
wangliu 已提交
33 34
namespace paddle_mobile {
namespace jni {
35

W
wangliu 已提交
36 37 38 39 40 41
using framework::DDim;
using framework::Program;
using framework::Tensor;
using paddle_mobile::CPU;
using std::string;

42 43
paddle_mobile::PaddleMobile<paddle_mobile::CPU> paddle_mobile;
static std::mutex shared_mutex;
W
wangliu 已提交
44

45
PaddleMobile<CPU> *getPaddleMobileInstance() { return &paddle_mobile; }
W
wangliu 已提交
46 47 48 49 50 51 52 53

string jstring2cppstring(JNIEnv *env, jstring jstr) {
  const char *cstr = env->GetStringUTFChars(jstr, 0);
  string cppstr(cstr);
  env->ReleaseStringUTFChars(jstr, cstr);
  return cppstr;
}

H
hjchen2 已提交
54 55 56 57
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_PML_load(JNIEnv *env,
                                                          jclass thiz,
                                                          jstring modelPath,
                                                          jboolean lodMode) {
58
  std::lock_guard<std::mutex> lock(shared_mutex);
59
  ANDROIDLOGI("load invoked");
W
wangliu 已提交
60
  bool optimize = true;
61 62 63 64
  bool isLoadOk = false;
#ifdef ENABLE_EXCEPTION
  try {
    isLoadOk = getPaddleMobileInstance()->Load(
65
        jstring2cppstring(env, modelPath), optimize, false, 1,
H
hjchen2 已提交
66
        static_cast<bool>(lodMode));
67 68 69 70 71 72
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
    isLoadOk = false;
  }
#else
  isLoadOk = getPaddleMobileInstance()->Load(jstring2cppstring(env, modelPath),
73
                                             optimize, false, 1,
H
hjchen2 已提交
74
                                             static_cast<bool>(lodMode));
xiebaiyuan's avatar
xiebaiyuan 已提交
75 76 77 78
#endif
  return static_cast<jboolean>(isLoadOk);
}

79
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_PML_loadQualified(
H
hjchen2 已提交
80
    JNIEnv *env, jclass thiz, jstring modelPath, jboolean lodMode) {
81 82
  std::lock_guard<std::mutex> lock(shared_mutex);

83 84 85
  ANDROIDLOGI("loadQualified invoked");
  bool optimize = true;
  bool qualified = true;
86 87 88 89 90
  bool isLoadOk = false;

#ifdef ENABLE_EXCEPTION
  try {
    isLoadOk = getPaddleMobileInstance()->Load(
91 92
        jstring2cppstring(env, modelPath), optimize, qualified, 1,
        static_cast<bool>(lodMode));
93 94 95 96 97 98
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
    isLoadOk = false;
  }
#else
  isLoadOk = getPaddleMobileInstance()->Load(jstring2cppstring(env, modelPath),
H
hjchen2 已提交
99 100
                                             optimize, qualified, 1,
                                             static_cast<bool>(lodMode));
101 102 103
#endif

  return static_cast<jboolean>(isLoadOk);
104 105
}

106
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_PML_loadCombined(
H
hjchen2 已提交
107 108
    JNIEnv *env, jclass thiz, jstring modelPath, jstring paramPath,
    jboolean lodMode) {
109
  std::lock_guard<std::mutex> lock(shared_mutex);
110
  ANDROIDLOGI("loadCombined invoked");
111
  bool optimize = true;
112 113 114 115 116 117
  bool isLoadOk = false;

#ifdef ENABLE_EXCEPTION
  try {
    isLoadOk = getPaddleMobileInstance()->Load(
        jstring2cppstring(env, modelPath), jstring2cppstring(env, paramPath),
118
        optimize, false, 1, static_cast<bool>(lodMode));
119 120 121 122 123
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
    isLoadOk = false;
  }
#else
H
hjchen2 已提交
124 125 126
  isLoadOk = getPaddleMobileInstance()->Load(
      jstring2cppstring(env, modelPath), jstring2cppstring(env, paramPath),
      optimize, false, 1, static_cast<bool>(lodMode));
127 128
#endif
  return static_cast<jboolean>(isLoadOk);
129 130
}

131
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_PML_loadCombinedQualified(
H
hjchen2 已提交
132 133
    JNIEnv *env, jclass thiz, jstring modelPath, jstring paramPath,
    jboolean lodMode) {
134
  std::lock_guard<std::mutex> lock(shared_mutex);
135 136 137
  ANDROIDLOGI("loadCombinedQualified invoked");
  bool optimize = true;
  bool qualified = true;
138 139 140 141 142 143
  bool isLoadOk = false;

#ifdef ENABLE_EXCEPTION
  try {
    isLoadOk = getPaddleMobileInstance()->Load(
        jstring2cppstring(env, modelPath), jstring2cppstring(env, paramPath),
144
        optimize, qualified, 1, static_cast<bool>(lodMode));
145 146 147 148 149
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
    isLoadOk = false;
  }
#else
H
hjchen2 已提交
150 151 152
  isLoadOk = getPaddleMobileInstance()->Load(
      jstring2cppstring(env, modelPath), jstring2cppstring(env, paramPath),
      optimize, qualified, 1, static_cast<bool>(lodMode));
153 154
#endif
  return static_cast<jboolean>(isLoadOk);
155 156
}

W
wangliu 已提交
157 158
JNIEXPORT jfloatArray JNICALL Java_com_baidu_paddle_PML_predictImage(
    JNIEnv *env, jclass thiz, jfloatArray buf, jintArray ddims) {
159 160
  std::lock_guard<std::mutex> lock(shared_mutex);

161
  ANDROIDLOGI("predictImage invoked");
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
  jfloatArray result = NULL;

#ifdef ENABLE_EXCEPTION
  ANDROIDLOGE("ENABLE_EXCEPTION!");

  try {
    jsize ddim_size = env->GetArrayLength(ddims);
    if (ddim_size != 4) {
      ANDROIDLOGE("ddims size not equal to 4");
    }
    jint *ddim_ptr = env->GetIntArrayElements(ddims, NULL);
    framework::DDim ddim = framework::make_ddim(
        {ddim_ptr[0], ddim_ptr[1], ddim_ptr[2], ddim_ptr[3]});
    int length = framework::product(ddim);
    int count = 0;
    float *dataPointer = nullptr;
    if (nullptr != buf) {
      dataPointer = env->GetFloatArrayElements(buf, NULL);
    }
    framework::Tensor input;
    input.Resize(ddim);
    auto input_ptr = input.mutable_data<float>();
    for (int i = 0; i < length; i++) {
      input_ptr[i] = dataPointer[i];
    }
187 188
    getPaddleMobileInstance()->Predict(input);
    auto output = getPaddleMobileInstance()->Fetch();
189 190 191 192 193 194 195 196 197 198 199
    count = output->numel();
    result = env->NewFloatArray(count);
    env->SetFloatArrayRegion(result, 0, count, output->data<float>());
    env->ReleaseIntArrayElements(ddims, ddim_ptr, 0);
    env->DeleteLocalRef(ddims);
    env->ReleaseFloatArrayElements(buf, dataPointer, 0);
    env->DeleteLocalRef(buf);
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
  }
#else
200
  jsize ddim_size = env->GetArrayLength(ddims);
W
wangliu 已提交
201 202
  if (ddim_size != 4) {
    ANDROIDLOGE("ddims size not equal to 4");
203 204
  }
  jint *ddim_ptr = env->GetIntArrayElements(ddims, NULL);
W
wangliu 已提交
205 206
  framework::DDim ddim = framework::make_ddim(
      {ddim_ptr[0], ddim_ptr[1], ddim_ptr[2], ddim_ptr[3]});
207
  int length = framework::product(ddim);
W
wangliu 已提交
208 209 210 211 212 213 214 215
  int count = 0;
  float *dataPointer = nullptr;
  if (nullptr != buf) {
    dataPointer = env->GetFloatArrayElements(buf, NULL);
  }
  framework::Tensor input;
  input.Resize(ddim);
  auto input_ptr = input.mutable_data<float>();
216
  for (int i = 0; i < length; i++) {
W
wangliu 已提交
217 218
    input_ptr[i] = dataPointer[i];
  }
219 220
  getPaddleMobileInstance()->Predict(input);
  auto output = getPaddleMobileInstance()->Fetch();
W
wangliu 已提交
221 222 223
  count = output->numel();
  result = env->NewFloatArray(count);
  env->SetFloatArrayRegion(result, 0, count, output->data<float>());
W
wangliu 已提交
224
  env->ReleaseIntArrayElements(ddims, ddim_ptr, 0);
225 226 227
  env->DeleteLocalRef(ddims);
  env->ReleaseFloatArrayElements(buf, dataPointer, 0);
  env->DeleteLocalRef(buf);
Z
zhaojiaying01 已提交
228
//  env->DeleteLocalRef(dataPointer);
229 230
#endif

231
  ANDROIDLOGI("predictImage finished");
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  return result;
}

JNIEXPORT jfloatArray JNICALL Java_com_baidu_paddle_PML_fetch(JNIEnv *env,
                                                              jclass thiz,
                                                              jstring varName) {
  jfloatArray result = NULL;

#ifdef ENABLE_EXCEPTION
  try {
    auto output =
        getPaddleMobileInstance()->Fetch(jstring2cppstring(env, varName));
    int count = output->numel();
    result = env->NewFloatArray(count);
    env->SetFloatArrayRegion(result, 0, count, output->data<float>());
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
  }
#else
  auto output =
      getPaddleMobileInstance()->Fetch(jstring2cppstring(env, varName));
  int count = output->numel();
  result = env->NewFloatArray(count);
  env->SetFloatArrayRegion(result, 0, count, output->data<float>());
#endif
257

W
wangliu 已提交
258 259 260
  return result;
}

W
wangliu 已提交
261
inline int yuv_to_rgb(int y, int u, int v, float *r, float *g, float *b) {
262 263 264
  int r1 = (int)(y + 1.370705 * (v - 128));                         // NOLINT
  int g1 = (int)(y - 0.698001 * (u - 128) - 0.703125 * (v - 128));  // NOLINT
  int b1 = (int)(y + 1.732446 * (u - 128));                         // NOLINT
265

266 267 268
  r1 = (int)fminf(255, fmaxf(0, r1));  // NOLINT
  g1 = (int)fminf(255, fmaxf(0, g1));  // NOLINT
  b1 = (int)fminf(255, fmaxf(0, b1));  // NOLINT
W
wangliu 已提交
269 270 271
  *r = r1;
  *g = g1;
  *b = b1;
272

W
wangliu 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
  return 0;
}
void convert_nv21_to_matrix(uint8_t *nv21, float *matrix, int width, int height,
                            int targetWidth, int targetHeight, float *means) {
  const uint8_t *yData = nv21;
  const uint8_t *vuData = nv21 + width * height;

  const int yRowStride = width;
  const int vuRowStride = width;

  float scale_x = width * 1.0 / targetWidth;
  float scale_y = height * 1.0 / targetHeight;

  for (int j = 0; j < targetHeight; ++j) {
    int y = j * scale_y;
    const uint8_t *pY = yData + y * yRowStride;
    const uint8_t *pVU = vuData + (y >> 1) * vuRowStride;
    for (int i = 0; i < targetWidth; ++i) {
      int x = i * scale_x;
      const int offset = ((x >> 1) << 1);
      float r = 0;
      float g = 0;
      float b = 0;
      yuv_to_rgb(pY[x], pVU[offset + 1], pVU[offset], &r, &g, &b);
      int r_index = j * targetWidth + i;
      int g_index = r_index + targetWidth * targetHeight;
      int b_index = g_index + targetWidth * targetHeight;
      matrix[r_index] = r - means[0];
      matrix[g_index] = g - means[1];
      matrix[b_index] = b - means[2];
303
    }
W
wangliu 已提交
304 305
  }
}
306

W
wangliu 已提交
307 308 309
JNIEXPORT jfloatArray JNICALL Java_com_baidu_paddle_PML_predictYuv(
    JNIEnv *env, jclass thiz, jbyteArray yuv_, jint imgwidth, jint imgHeight,
    jintArray ddims, jfloatArray meanValues) {
310 311
  std::lock_guard<std::mutex> lock(shared_mutex);

W
wangliu 已提交
312
  ANDROIDLOGI("predictYuv invoked");
313 314 315 316 317 318 319 320 321 322 323 324
  jfloatArray result = NULL;

#ifdef ENABLE_EXCEPTION
  try {
    jsize ddim_size = env->GetArrayLength(ddims);
    if (ddim_size != 4) {
      ANDROIDLOGE("ddims size not equal to 4");
    }
    jint *ddim_ptr = env->GetIntArrayElements(ddims, NULL);
    framework::DDim ddim = framework::make_ddim(
        {ddim_ptr[0], ddim_ptr[1], ddim_ptr[2], ddim_ptr[3]});
    int length = framework::product(ddim);
325
    float matrix[length];  // NOLINT
326 327 328 329 330
    jbyte *yuv = env->GetByteArrayElements(yuv_, NULL);
    float *meansPointer = nullptr;
    if (nullptr != meanValues) {
      meansPointer = env->GetFloatArrayElements(meanValues, NULL);
    }
331 332
    convert_nv21_to_matrix(reinterpret_cast<uint8_t *>(yuv), matrix, imgwidth,
                           imgHeight, ddim[3], ddim[2], meansPointer);
333 334 335 336 337 338 339
    int count = 0;
    framework::Tensor input;
    input.Resize(ddim);
    auto input_ptr = input.mutable_data<float>();
    for (int i = 0; i < length; i++) {
      input_ptr[i] = matrix[i];
    }
340 341
    getPaddleMobileInstance()->Predict(input);
    auto output = getPaddleMobileInstance()->Fetch();
342 343 344 345 346 347 348 349 350 351 352
    count = output->numel();
    result = env->NewFloatArray(count);
    env->SetFloatArrayRegion(result, 0, count, output->data<float>());
    env->ReleaseByteArrayElements(yuv_, yuv, 0);
    env->ReleaseIntArrayElements(ddims, ddim_ptr, 0);
    env->ReleaseFloatArrayElements(meanValues, meansPointer, 0);
    ANDROIDLOGI("predictYuv finished");
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
  }
#else
W
wangliu 已提交
353 354 355 356 357 358 359 360
  jsize ddim_size = env->GetArrayLength(ddims);
  if (ddim_size != 4) {
    ANDROIDLOGE("ddims size not equal to 4");
  }
  jint *ddim_ptr = env->GetIntArrayElements(ddims, NULL);
  framework::DDim ddim = framework::make_ddim(
      {ddim_ptr[0], ddim_ptr[1], ddim_ptr[2], ddim_ptr[3]});
  int length = framework::product(ddim);
361
  float matrix[length];  // NOLINT
W
wangliu 已提交
362 363 364 365 366
  jbyte *yuv = env->GetByteArrayElements(yuv_, NULL);
  float *meansPointer = nullptr;
  if (nullptr != meanValues) {
    meansPointer = env->GetFloatArrayElements(meanValues, NULL);
  }
367 368
  convert_nv21_to_matrix((uint8_t *)yuv, matrix, imgwidth,  // NOLINT
                         imgHeight, ddim[3], ddim[2], meansPointer);
W
wangliu 已提交
369 370 371 372 373 374 375
  int count = 0;
  framework::Tensor input;
  input.Resize(ddim);
  auto input_ptr = input.mutable_data<float>();
  for (int i = 0; i < length; i++) {
    input_ptr[i] = matrix[i];
  }
376 377
  getPaddleMobileInstance()->Predict(input);
  auto output = getPaddleMobileInstance()->Fetch();
W
wangliu 已提交
378 379 380 381 382 383 384
  count = output->numel();
  result = env->NewFloatArray(count);
  env->SetFloatArrayRegion(result, 0, count, output->data<float>());
  env->ReleaseByteArrayElements(yuv_, yuv, 0);
  env->ReleaseIntArrayElements(ddims, ddim_ptr, 0);
  env->ReleaseFloatArrayElements(meanValues, meansPointer, 0);
  ANDROIDLOGI("predictYuv finished");
385 386
#endif

W
wangliu 已提交
387
  return result;
388
}
xiebaiyuan's avatar
xiebaiyuan 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
JNIEXPORT jlongArray JNICALL
Java_com_baidu_paddle_PML_predictLod(JNIEnv *env, jclass thiz, jlongArray buf) {
  std::lock_guard<std::mutex> lock(shared_mutex);

  jlong *ddim_ptr = env->GetLongArrayElements(buf, NULL);
  jsize ddim_size = env->GetArrayLength(buf);
  std::vector<int64_t> ids;

  for (int i = 0; i < ddim_size; ++i) {
    jlong x = ddim_ptr[i];
    ids.push_back((int64_t)x);
  }

  paddle_mobile::framework::LoDTensor words;

  auto size = static_cast<int>(ids.size());

  paddle_mobile::framework::LoD lod{{0, ids.size()}};
  DDim dims{size, 1};
  words.Resize(dims);
  words.set_lod(lod);
  auto *pdata = words.mutable_data<int64_t>();
  size_t n = words.numel() * sizeof(int64_t);
  memcpy(pdata, ids.data(), n);
413 414
  paddle_mobile.Predict(words);
  auto vec_result = paddle_mobile.Fetch();
xiebaiyuan's avatar
xiebaiyuan 已提交
415 416 417 418 419 420 421
  int count = vec_result->numel();
  jlongArray result = NULL;
  ANDROIDLOGE("predict nlp size %d", count);

  result = env->NewLongArray(count);
  env->SetLongArrayRegion(result, 0, count, vec_result->data<int64_t>());

E
eclipsess 已提交
422
  env->ReleaseLongArrayElements(buf, ddim_ptr, 0);
xiebaiyuan's avatar
xiebaiyuan 已提交
423 424
  return result;
}
425

426 427 428
JNIEXPORT void JNICALL Java_com_baidu_paddle_PML_setThread(JNIEnv *env,
                                                           jclass thiz,
                                                           jint threadCount) {
429 430
  std::lock_guard<std::mutex> lock(shared_mutex);

431
  ANDROIDLOGI("setThreadCount %d", threadCount);
432 433
#ifdef ENABLE_EXCEPTION
  try {
434
    getPaddleMobileInstance()->SetThreadNum(static_cast<int>(threadCount));
435 436 437 438
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
  }
#else
439
  getPaddleMobileInstance()->SetThreadNum(static_cast<int>(threadCount));
440
#endif
441 442
}

W
wangliu 已提交
443
JNIEXPORT void JNICALL Java_com_baidu_paddle_PML_clear(JNIEnv *env,
444
                                                       jclass thiz) {
445 446 447 448 449 450 451 452 453
  std::lock_guard<std::mutex> lock(shared_mutex);

#ifdef ENABLE_EXCEPTION
  try {
    getPaddleMobileInstance()->Clear();
  } catch (paddle_mobile::PaddleMobileException &e) {
    ANDROIDLOGE("jni got an PaddleMobileException! ", e.what());
  }
#else
454
  getPaddleMobileInstance()->Clear();
455
#endif
456
}
W
wangliu 已提交
457 458 459 460 461 462 463 464 465

}  // namespace jni
}  // namespace paddle_mobile

#ifdef __cplusplus
}
#endif

#endif