a
554325746@qq.com
2020-01-15 956063ff14bc75e3a2a97c7bcaa06b9edc84ad24
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
#include <linux/gpio.h>
 
#include <jni.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
 
#include "FiStdDefEx.h"
#include "THFaceImage_i.h"
#include <setjmp.h>
 
#include "FaceDetectHelper.h"
#include "LogUtil.h"
 
#include <memory>
#include <opencv2/opencv.hpp>
#include "THFeature_i.h"
 
#include <map>
#include <list>
#include <algorithm>
 
#include <memory>
#include <unordered_map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
 
#include "RgbDetect.h"
#include "GrayDetect.h"
#include "LivenessDetect.h"
 
#include "FiStdDefEx.h"
 
#include <memory>
#include "THFeature_i.h"
 
#include "FaceDetectHelper.h"
#include "LogUtil.h"
#include <memory>
#include <sstream>
#include "TrackingTrigger.h"
#include <map>
 
#include <memory>
#include "THFeature_i.h"
#include <sys/time.h>
#include <time.h>
#include <iostream>
#include <string>
#include <cstring>
#include <android/log.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
 
#define TAG "jni ndk "
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)
extern "C" {
}
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,"testff",__VA_ARGS__)
 
 
unsigned char* ConvertJByteaArrayToChars(JNIEnv *env, jbyteArray bytearray)
{
    unsigned char *chars = NULL;
    jbyte *bytes;
    bytes = env->GetByteArrayElements(bytearray, 0);
    int chars_len = env->GetArrayLength(bytearray);
    chars = new unsigned char[chars_len + 1];
    memset(chars,0,chars_len + 1);
    memcpy(chars, bytes, chars_len);
    chars[chars_len] = 0;
    env->ReleaseByteArrayElements(bytearray, bytes, 0);
 
    return chars;
}
 
#include "yuv2bgr.h"
extern "C" JNIEXPORT jbyteArray
JNICALL
Java_com_basic_security_utils_FaceId_yuv420p2rgb24(
        JNIEnv *env, jobject, jbyteArray yuvbuffer, jbyteArray rgbbuffer, int width, int height) {
 
    unsigned char *yuvData = ConvertJByteaArrayToChars(env,yuvbuffer);
//    unsigned char *rgbData = ConvertJByteaArrayToChars(env,rgbbuffer);
    yuv420p_to_rgb24_c(yuvData, (unsigned char*)rgbbuffer, width, height);
 
    delete yuvData;
 
//
////    jbyteArray ret = (*env)->NewByteArray(640*480*3);
//    jbyte* p = env-> GetByteArrayElements(rgbbuffer, 0);
//    FaceDetectHelper::getInstance()->yuv420p_to_rgb24_jni(env, yuvbuffer, p, width, height);
////    LogUtil::log(faces);
////    std::cout << faces <<std::endl;
////    return env->NewStringUTF(faces.c_str());
 
    return rgbbuffer;
}
 
 
mutex featureListMutex;
 
mutex tempFeatureLock;
 
extern "C" JNIEXPORT jboolean
JNICALL
Java_com_basic_security_utils_FaceId_initSdk(
        JNIEnv *env, jobject, jstring jModelPath) {
    const char *modelPath = env->GetStringUTFChars(jModelPath, 0);
    jboolean success = false;
    success = FaceDetectHelper::getInstance()->initSdk(modelPath);
 
    return success;
 
 
}
 
 
jint getIntValue(JNIEnv *env, jobject detectedResult, char *fieldName) {
    jclass detectedResultClass = env->GetObjectClass(detectedResult);
    jfieldID isRgbFieldId = env->GetFieldID(detectedResultClass, fieldName, "I");
    jint intValue = env->GetIntField(detectedResult, isRgbFieldId);
    return intValue;
}
 
jboolean getBooleanValue(JNIEnv *env, jobject detectedResult, char *fieldName) {
    jclass detectedResultClass = env->GetObjectClass(detectedResult);
    jfieldID isRgbFieldId = env->GetFieldID(detectedResultClass, fieldName, "Z");
    jboolean isRgb = env->GetBooleanField(detectedResult, isRgbFieldId);
    return isRgb;
}
bool useFeatureList = false;
namespace main {
    BYTE features[10][2560];
    int featureSize = 2560;
    TrackingTrigger trackingTrigger(0.8);
    ScoredRect sr;
    long track_id[10];
    bool liveness[10];
    string featureNames[10];
 
    double prevExtractFeatureTime = 0;
 
    unsigned char *rgbBuffer = new unsigned char[640 * 480 * 3];
    unsigned char *grayBuffer = new unsigned char[640 * 480 * 3];
    THFI_FacePos rgbFps1[10];
    THFI_FacePos grayFps1[10];
 
    double msecond() {
        struct timeval tv;
        gettimeofday(&tv, 0);
        return (tv.tv_sec * 1.0e3 + tv.tv_usec * 1.0e-3);
    }
}
 
void setIntValue(JNIEnv *env, jobject detectedResult, char *fieldName, jint value) {
    jclass detectedResultClass = env->GetObjectClass(detectedResult);
    jfieldID isRgbFieldId = env->GetFieldID(detectedResultClass, fieldName, "I");
    env->SetIntField(detectedResult, isRgbFieldId, value);
}
 
extern "C" JNIEXPORT void
JNICALL
Java_com_basic_security_utils_FaceId_detectFace(
        JNIEnv *env, jobject, jobject detectedResult) {
    jboolean isRgb = getBooleanValue(env, detectedResult, "isRgb");
    int width = getIntValue(env, detectedResult, "width");
    int height = getIntValue(env, detectedResult, "height");
    jboolean shouldExtractFeature = getBooleanValue(env, detectedResult, "shouldExtractFeature");
    jclass detectedResultClass = env->GetObjectClass(detectedResult);
    jfieldID bgrDataFieldId = env->GetFieldID(detectedResultClass, "bgrData", "[B");
    jobject bgrData = env->GetObjectField(detectedResult, bgrDataFieldId);
    jbyteArray bgrDataByteArray = reinterpret_cast<jbyteArray>(bgrData);
    int len = env->GetArrayLength(bgrDataByteArray);
 
    if (isRgb) {
        env->GetByteArrayRegion(bgrDataByteArray, 0, len,
                                reinterpret_cast<jbyte *>(main::rgbBuffer));
        int face_nums = THFI_DetectFace(0, main::rgbBuffer, 24, width, height, main::rgbFps1, 10,
                                        360);
        int featureCount = 0;
        for (int i = 0; i < face_nums; i++) {
            try {
                THFI_FacePos fps;
                fps = main::rgbFps1[i];
                ScoredRect scoredRect{fps.fAngle.confidence, {
                        fps.rcFace.left,
                        fps.rcFace.top,
                        fps.rcFace.right,
                        fps.rcFace.bottom
                }, -1, map<string, string>()};
                bool not_duplicate = main::trackingTrigger.triggerOnce(scoredRect);
                bool track_id_changed = (main::track_id[i] != scoredRect.id);
                main::track_id[i] = scoredRect.id;
                if (main::track_id[i] == 1) {
                    int m = 0;
                }
                if (main::track_id[i] == -1) {
                    continue;
                }
                int liveness = 0;
                main::liveness[i] = liveness;
                int featureId = i;
                double d1 = main::msecond();
                if ((track_id_changed ||
                     (main::msecond() - main::prevExtractFeatureTime) > 2 * 1000)
                    && shouldExtractFeature > 0) {
                    memset(main::features[i], 0, main::featureSize);
                    int ret = EF_Extract(0, main::rgbBuffer, width, height, 3, main::rgbFps1,
                                         main::features[i]);
                    if (ret == 1) {
                        featureCount++;
                        main::prevExtractFeatureTime = main::msecond();
                    } else {
                        featureId = -1;
                    }
                }
 
                jclass facePositionClass = env->FindClass("com/basic/security/utils/FacePosition");
                jmethodID facePositionClassMethodID = env->GetMethodID(facePositionClass, "<init>",
                                                                       "(I)V");
                jobject facePositionObject = env->NewObject(facePositionClass,
                                                            facePositionClassMethodID, 5);
 
 
            } catch (exception &e) {
                LogUtil::log(e.what());
            }
        }
        setIntValue(env, detectedResult, "featureCount", featureCount);
    } else {
        env->GetByteArrayRegion(bgrDataByteArray, 0, len,
                                reinterpret_cast<jbyte *>(main::grayBuffer));
        int face_nums = THFI_DetectFace(0, main::grayBuffer, 24, width, height, main::grayFps1, 10,
                                        360);
    }
    int i = 10;
}
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_rgbDetectFace(
        JNIEnv *env, jobject, jstring jModelPath, jstring jRgbFileName, jint width, int height,
        jstring baseFeatureName, int shouldExtractFeature, bool useGrayCamera,
        int detectFaceCount) {
    string faces = FaceDetectHelper::getInstance()->detectRealFace(
            env->GetStringUTFChars(jModelPath, 0), env->GetStringUTFChars(jRgbFileName, 0), nullptr,
            width, height, env->GetStringUTFChars(baseFeatureName, 0), shouldExtractFeature,
            useGrayCamera, detectFaceCount);
    LogUtil::log(faces);
    return env->NewStringUTF(faces.c_str());
}
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_rgbDetectFace2(
        JNIEnv *env, jobject, jstring jModelPath, jstring jRgbFileName, jint width, int height,
        jstring baseFeatureName, int shouldExtractFeature, bool useGrayCamera,
        int detectFaceCount, jbyteArray bgrArray) {
    string faces = FaceDetectHelper::getInstance()->detectRealFace2(env,
            env->GetStringUTFChars(jModelPath, 0), env->GetStringUTFChars(jRgbFileName, 0), nullptr,
            width, height, env->GetStringUTFChars(baseFeatureName, 0), shouldExtractFeature,
            useGrayCamera, detectFaceCount, bgrArray);
    LogUtil::log(faces);
    return env->NewStringUTF(faces.c_str());
}
 
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_rgbDetectFace4(
        JNIEnv *env, jobject,jint channel, jstring jModelPath, jstring jRgbFileName, jint width, int height,
        jstring baseFeatureName, int shouldExtractFeature, bool useGrayCamera,
        int detectFaceCount, jbyteArray bgrArray) {
    string faces = FaceDetectHelper::getInstance()->detectRealFace4(env,
                                                                    channel, env->GetStringUTFChars(jModelPath, 0), env->GetStringUTFChars(jRgbFileName, 0), nullptr,
                                                                    width, height, env->GetStringUTFChars(baseFeatureName, 0), shouldExtractFeature,
                                                                    useGrayCamera, detectFaceCount, bgrArray);
    LogUtil::log(faces);
    return env->NewStringUTF(faces.c_str());
}
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_rgbDetectFace3(
        JNIEnv *env, jobject, jint channel, jstring jModelPath, jint width, int height,
        jstring baseFeatureName, int shouldExtractFeature, bool useGrayCamera,
        int detectFaceCount, jbyteArray nv21Array) {
    string faces = FaceDetectHelper::getInstance()->detectRealFace3(channel, env,
                                                                    env->GetStringUTFChars(jModelPath, 0),
                                                                    width, height, env->GetStringUTFChars(baseFeatureName, 0), shouldExtractFeature,
                                                                    useGrayCamera, detectFaceCount, nv21Array);
    LogUtil::log(faces);
    return env->NewStringUTF(faces.c_str());
}
 
extern "C" JNIEXPORT jbyteArray
JNICALL
Java_com_basic_security_utils_FaceId_extractFeature(
        JNIEnv *env, jobject, jstring jpgFileName) {
    return FaceDetectHelper::getInstance()->extractFeature(env,
                                                           env->GetStringUTFChars(jpgFileName, 0));
}
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_facePosition(
        JNIEnv *env, jobject, jstring jpgFileName) {
    string facePosition = FaceDetectHelper::getInstance()->facePosition(env,
                                                           env->GetStringUTFChars(jpgFileName, 0));
    return env->NewStringUTF(facePosition.c_str());
}
 
extern "C" JNIEXPORT jbyteArray
JNICALL
Java_com_basic_security_utils_FaceId_extractFeature1(
        JNIEnv *env, jobject, jbyteArray bgrByteArray, int width, int height) {
    return FaceDetectHelper::getInstance()->extractFeature(env, bgrByteArray, width, height);
}
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_grayDetectFace(
        JNIEnv *env, jobject, jstring jModelPath, jstring jGrayFileName, jint width, int height,
        int detectFaceCount) {
    string faces = FaceDetectHelper::getInstance()->detectRealFace(
            env->GetStringUTFChars(jModelPath, 0), nullptr,
            env->GetStringUTFChars(jGrayFileName, 0), width, height,
            nullptr, 0, false, detectFaceCount);
    LogUtil::log(faces);
    return env->NewStringUTF(faces.c_str());
}
 
extern "C" JNIEXPORT void
JNICALL
Java_com_basic_security_utils_FaceId_cropFace(
        JNIEnv *env, jobject, jstring frameJpgPath, jstring faceJpgPath, int width, int height,
        int x1, int y1, int x2, int y2) {
    try {
        cv::Mat img = cv::imread(env->GetStringUTFChars(frameJpgPath, 0));
        if (!img.empty()) {
            /*cv::Rect roi;
            roi.x = x1;
            roi.y = y1;
            roi.width = x2 - x1;
            roi.height = y2 - y1;
            cv::Mat crop = img(roi);
            //env->GetStringUTFChars(faceJpgPath, 0)
            cv::String name;
            cv::imwrite(name, crop);
             */
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
}
 
jbyteArray as_byte_array(JNIEnv *env, unsigned char *buf, int len) {
    jbyteArray array = env->NewByteArray(len);
    env->SetByteArrayRegion(array, 0, len, reinterpret_cast<jbyte *>(buf));
    return array;
}
 
unsigned char *as_unsigned_char_array(JNIEnv *env, jbyteArray array) {
    int len = env->GetArrayLength(array);
    unsigned char *buf = new unsigned char[len];
    env->GetByteArrayRegion(array, 0, len, reinterpret_cast<jbyte *>(buf));
    return buf;
}
 
unordered_map<string, shared_ptr<vector<unsigned char>>> featureMap;
list<pair<string, shared_ptr<vector<unsigned char>>>> featureList;
 
unordered_map<string, shared_ptr<vector<unsigned char>>> allFeatureMap;
 
extern "C" JNIEXPORT void
JNICALL
Java_com_basic_security_utils_FaceId_addFeatureToDb(
        JNIEnv *env, jobject, jstring id, jbyteArray featureBuffer) {
    try {
        if (featureBuffer == nullptr) {
            return;
        }
        if (featureMap.size() < 100 || 1 == 1) {
            if (!useFeatureList) {
                unsigned int max_size = featureMap.max_size();
                {
                    int len = env->GetArrayLength(featureBuffer);
                    shared_ptr<vector<unsigned char>> feature = make_shared<vector<unsigned char>>(len);
                    env->GetByteArrayRegion(featureBuffer, 0, len,
                                            reinterpret_cast<jbyte *>(feature.get()->data()));
                    const char *sid = env->GetStringUTFChars(id, 0);
                    featureMap[sid] = feature;
                }
            }
            if (useFeatureList) {
                unsigned int max_size = featureMap.max_size();
                {
                    int len = env->GetArrayLength(featureBuffer);
                    shared_ptr<vector<unsigned char>> feature = make_shared<vector<unsigned char>>(len);
                    env->GetByteArrayRegion(featureBuffer, 0, len,
                                            reinterpret_cast<jbyte *>(feature.get()->data()));
                    const char *sid = env->GetStringUTFChars(id, 0);
                    featureListMutex.lock();
                    featureList.push_back({sid, feature});
                    featureListMutex.unlock();
                }
            }
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
}
 
 
extern "C" JNIEXPORT void
JNICALL
Java_com_basic_security_utils_FaceId_addFeatureToAllDb(
        JNIEnv *env, jobject, jstring id, jbyteArray featureBuffer) {
    try {
        if (featureBuffer == nullptr) {
            return;
        }
        if (allFeatureMap.size() < 100 || 1 == 1) {
            if (!useFeatureList) {
                unsigned int max_size = allFeatureMap.max_size();
                {
                    int len = env->GetArrayLength(featureBuffer);
                    shared_ptr<vector<unsigned char>> feature = make_shared<vector<unsigned char>>(len);
                    env->GetByteArrayRegion(featureBuffer, 0, len,
                                            reinterpret_cast<jbyte *>(feature.get()->data()));
                    const char *sid = env->GetStringUTFChars(id, 0);
                    allFeatureMap[sid] = feature;
                }
            }
            /*if (useFeatureList) {
                unsigned int max_size = allFeatureMap.max_size();
                {
                    int len = env->GetArrayLength(featureBuffer);
                    shared_ptr<vector<unsigned char>> feature = make_shared<vector<unsigned char>>(len);
                    env->GetByteArrayRegion(featureBuffer, 0, len,
                                            reinterpret_cast<jbyte *>(feature.get()->data()));
                    const char *sid = env->GetStringUTFChars(id, 0);
                    featureListMutex.lock();
                    featureList.push_back({sid, feature});
                    featureListMutex.unlock();
                }
            }*/
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
}
 
 
unordered_map<string, shared_ptr<vector<unsigned char>>> tempFeatureMap;
list<pair<string, shared_ptr<vector<unsigned char>>>> tempFeatureList;
 
extern "C" JNIEXPORT void
JNICALL
Java_com_basic_security_utils_FaceId_addFeatureToTempDb(
        JNIEnv *env, jobject, jstring id, jbyteArray featureBuffer) {
    try {
        if (tempFeatureMap.size() < 100 || 1 == 1) {
            if (!useFeatureList) {
                unsigned int max_size = tempFeatureMap.max_size();
                {
                    int len = env->GetArrayLength(featureBuffer);
                    shared_ptr<vector<unsigned char>> feature = make_shared<vector<unsigned char>>(len);
                    env->GetByteArrayRegion(featureBuffer, 0, len,
                                            reinterpret_cast<jbyte *>(feature.get()->data()));
                    const char *sid = env->GetStringUTFChars(id, 0);
                    tempFeatureMap[sid] = feature;
                }
            } else {
                unsigned int max_size = tempFeatureMap.max_size();
                {
                    int len = env->GetArrayLength(featureBuffer);
                    shared_ptr<vector<unsigned char>> feature = make_shared<vector<unsigned char>>(len);
                    env->GetByteArrayRegion(featureBuffer, 0, len,
                                            reinterpret_cast<jbyte *>(feature.get()->data()));
                    const char *sid = env->GetStringUTFChars(id, 0);
                    tempFeatureLock.lock();
                    tempFeatureList.push_front({sid, feature});
                    tempFeatureLock.unlock();
                }
            }
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
}
 
extern "C" JNIEXPORT jfloat
JNICALL
Java_com_basic_security_utils_FaceId_compareFeature(
        JNIEnv *env, jobject, jbyteArray featureBuffer1, jbyteArray featureBuffer2) {
    float score = 0;
    try {
        if (!featureBuffer1 || !featureBuffer2) {
            return score;
        }
        unsigned char *buf1 = as_unsigned_char_array(env, featureBuffer1);
        unsigned char *buf2 = as_unsigned_char_array(env, featureBuffer2);
        score = EF_Compare(buf1, buf2)*100;
        delete[] buf1;
        delete[] buf2;
 
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
    return score;
}
 
 
unsigned char buf[2560];
 
void
moveToFront(
        std::list<pair<string, shared_ptr<vector<unsigned char>>>>& list,
        std::list<pair<string, shared_ptr<vector<unsigned char>>>>::iterator element )
{
    if ( element != list.begin() ) {
        list.splice( list.begin(), list, element, std::next( element ) );
    }
}
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_compareFeatureInDb(
        JNIEnv *env, jobject, jbyteArray featureBuffer, jint minScore) {
    float score = 0;
    string result = ",0";
    try {
        env->GetByteArrayRegion(featureBuffer, 0, 2560, reinterpret_cast<jbyte *>(buf));
        if (!useFeatureList) {
            for (auto const &featureItem : featureMap) {
                string id = featureItem.first;
                unsigned char *data = featureItem.second.get()->data();
                printf("%s\n", id.c_str());
                score = EF_Compare(buf, data)*100;
                int i = 10;
                if (score >= minScore) {
//                LOGI("the score is :%d",score);
                    result = "";
                    result.append(id);
                    result.append(",");
                    result.append(to_string(score));
                    break;
                }
            }
        } else {
            featureListMutex.lock();
            for (auto featureItem = begin(featureList); featureItem != end(featureList); featureItem++) {
                string id = featureItem->first;
                unsigned char *data = featureItem->second.get()->data();
                printf("%s\n", id.c_str());
                score = EF_Compare(buf, data)*100;
                int i = 10;
                if (score >= minScore) {
//                LOGI("the score is :%d",score);
                    moveToFront(featureList, featureItem);
                    result = "";
                    result.append(id);
                    result.append(",");
                    result.append(to_string(score));
                    break;
                }
            }
            featureListMutex.unlock();
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
    return env->NewStringUTF(result.c_str());
}
 
 
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_compareFeatureInAllDb(
        JNIEnv *env, jobject, jbyteArray featureBuffer, jint minScore) {
    float score = 0;
    string result = ",0";
    try {
        env->GetByteArrayRegion(featureBuffer, 0, 2560, reinterpret_cast<jbyte *>(buf));
        if (!useFeatureList) {
            for (auto const &featureItem : allFeatureMap) {
                string id = featureItem.first;
                unsigned char *data = featureItem.second.get()->data();
                printf("%s\n", id.c_str());
                score = EF_Compare(buf, data)*100;
                int i = 10;
                if (score >= minScore) {
                    result = "";
                    result.append(id);
                    result.append(",");
                    result.append(to_string(score));
                    break;
                }
            }
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
    return env->NewStringUTF(result.c_str());
}
 
 
unsigned char tempFeatureBuf[2560];
 
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_compareFeatureInTempDb(
        JNIEnv *env, jobject, jbyteArray featureBuffer, jint minScore) {
    float score = 0;
    string result = ",0";
    try {
        env->GetByteArrayRegion(featureBuffer, 0, 2560, reinterpret_cast<jbyte *>(tempFeatureBuf));
        if (!useFeatureList) {
            for (auto const &featureItem : tempFeatureMap) {
                string id = featureItem.first;
                unsigned char *data = featureItem.second.get()->data();
                printf("%s\n", id.c_str());
                score = EF_Compare(tempFeatureBuf, data)*100;
                int i = 10;
                if (score >= minScore) {
//                LOGI("the score is :%d",score);
                    result = "";
                    result.append(id);
                    result.append(",");
                    result.append(to_string(score));
                    break;
                }
            }
        } else {
            tempFeatureLock.lock();
            for (auto featureItem = begin(tempFeatureList); featureItem != end(tempFeatureList); featureItem++) {
                string id = featureItem->first;
                unsigned char *data = featureItem->second.get()->data();
                printf("%s\n", id.c_str());
                score = EF_Compare(tempFeatureBuf, data)*100;
                int i = 10;
                if (score >= minScore) {
//                LOGI("the score is :%d",score);
                    moveToFront(tempFeatureList, featureItem);
                    result = "";
                    result.append(id);
                    result.append(",");
                    result.append(to_string(score));
                    break;
                }
            }
            tempFeatureLock.unlock();
        }
 
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
    return env->NewStringUTF(result.c_str());
}
 
 
extern "C" JNIEXPORT void
JNICALL
Java_com_basic_security_utils_FaceId_removeFeatureFromTempDb(JNIEnv *env, jobject, jstring id) {
    try {
        if (!useFeatureList) {
            tempFeatureMap.erase(env->GetStringUTFChars(id, 0));
        } else {
            auto personId = env->GetStringUTFChars(id, 0);
            tempFeatureLock.lock();
            for (auto it = begin(tempFeatureList); it != end(tempFeatureList); it++) {
                if (it->first == personId) {
//                    tempFeatureList.remove(*it);
                    printf("tempFeatureList1 before %d\n", tempFeatureList.size());
                    tempFeatureList.erase(it);
                    printf("tempFeatureList1 end %d\n", tempFeatureList.size());
                    break;
                }
            }
            tempFeatureLock.unlock();
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
}
 
extern "C" JNIEXPORT void
JNICALL
Java_com_basic_security_utils_FaceId_removeFeatureFromDb(JNIEnv *env, jobject, jstring id) {
    try {
        if (!useFeatureList) {
            featureMap.erase(env->GetStringUTFChars(id, 0));
        } else {
            auto personId = env->GetStringUTFChars(id, 0);
            featureListMutex.lock();
            for (auto it = begin(featureList); it != end(featureList); it++) {
                if (it->first == personId) {
                    printf("featureList erase before %d\n", featureList.size());
                    featureList.erase(it);
                    printf("featureList erase end %d\n", featureList.size());
                    break;
                }
            }
            featureListMutex.unlock();
        }
    } catch (exception &e) {
        LogUtil::log(e.what());
    }
}
 
//static double r2d(AVRational r) {
//    return r.num == 0 || r.den == 0 ? 0 : (double) r.num / (double) r.den;
//}
 
//当前时间戳 clock
long long GetNowMs() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    int sec = tv.tv_sec % 360000;
    long long t = sec * 1000 + tv.tv_usec / 1000;
    return t;
}
 
extern "C"
JNIEXPORT
jint JNI_OnLoad(JavaVM *vm, void *res) {
    //av_jni_set_java_vm(vm, 0);
    return JNI_VERSION_1_4;
}
 
 
extern "C"
JNIEXPORT void JNICALL
Java_com_basic_security_widget_H264Player_Open(JNIEnv *env, jobject instance, jstring url_,
                                               jobject surface) {
    const char *path = env->GetStringUTFChars(url_, 0);
//    av_register_all();
//    avformat_network_init();
//    avcodec_register_all();
//    AVFormatContext *ic = NULL;
//    int re = avformat_open_input(&ic, path, 0, 0);
//    if (re != 0) { return; }
//    re = avformat_find_stream_info(ic, 0);
//    if (re != 0) {}
//    int fps = 0;
//    int videoStream = 0;
//    int audioStream = 1;
//    for (int i = 0; i < ic->nb_streams; i++) {
//        AVStream *as = ic->streams[i];
//        if (as->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
//            videoStream = i;
//            fps = r2d(as->avg_frame_rate);
//        } else if (as->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
//            audioStream = i;
//        }
//    }
//    audioStream = av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
//
//    AVCodec *codec = avcodec_find_decoder(ic->streams[videoStream]->codecpar->codec_id);
//    codec = avcodec_find_decoder_by_name("h264_mediacodec");
//    if (!codec) { return; }
//    AVCodecContext *vc = avcodec_alloc_context3(codec);
//    avcodec_parameters_to_context(vc, ic->streams[videoStream]->codecpar);
//    vc->thread_count = 8;
//    re = avcodec_open2(vc, 0, 0);
//    if (re != 0) { return; }
//    AVPacket *pkt = av_packet_alloc();
//    AVFrame *frame = av_frame_alloc();
//    long long start = GetNowMs();
//    int frameCount = 0;
//    SwsContext *vctx = NULL;
//    int outWidth = 640;
//    int outHeight = 480;
//    char *rgb = new char[1920 * 1080 * 4];
//    char *pcm = new char[48000 * 4 * 2];
//    ANativeWindow *nwin = ANativeWindow_fromSurface(env, surface);
//    ANativeWindow_setBuffersGeometry(nwin, outWidth, outHeight, WINDOW_FORMAT_RGBA_8888);
//    ANativeWindow_Buffer wbuf;
//
//    for (;;) {
//        if (GetNowMs() - start >= 3000) {
//            start = GetNowMs();
//            frameCount = 0;
//        }
//
//        int re = av_read_frame(ic, pkt);
//        if (re != 0) {
//            int pos = 20 * r2d(ic->streams[videoStream]->time_base);
//            av_seek_frame(ic, videoStream, pos, AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME);
//            continue;
//        }
//        AVCodecContext *cc = vc;
//        re = avcodec_send_packet(cc, pkt);
//        //清理
//        int p = pkt->pts;
//        av_packet_unref(pkt);
//        if (re != 0) {
//            continue;
//        }
//        for (;;) {
//            re = avcodec_receive_frame(cc, frame);
//            if (re != 0) {
//                break;
//            }
//            if (cc == vc) {
//                frameCount++;
//                vctx = sws_getCachedContext(vctx,
//                                            frame->width,
//                                            frame->height,
//                                            (AVPixelFormat) frame->format,
//                                            outWidth,
//                                            outHeight,
//                                            AV_PIX_FMT_RGBA,
//                                            SWS_FAST_BILINEAR,
//                                            0, 0, 0
//                );
//                if (!vctx) {}
//                else {
//                    uint8_t *data[AV_NUM_DATA_POINTERS] = {0};
//                    data[0] = (uint8_t *) rgb;
//                    int lines[AV_NUM_DATA_POINTERS] = {0};
//                    lines[0] = outWidth * 4;
//                    int h = sws_scale(vctx,
//                                      (const uint8_t **) frame->data,
//                                      frame->linesize, 0,
//                                      frame->height,
//                                      data, lines);
////                    LOGW("sws_scale = %d",h);
//                    if (h > 0) {
//                        ofstream ofs;
//                        ofs.open("/sdcard/ffmpeg.rgb", ios::binary);
//                        ofs.write((char *) rgb, outWidth * outHeight * 4);
//                        ofs.close();
//
//                        ANativeWindow_lock(nwin, &wbuf, 0);
//                        uint8_t *dst = (uint8_t *) wbuf.bits;
//                        memcpy(dst, rgb, outWidth * outHeight * 4);
//                        ANativeWindow_unlockAndPost(nwin);
//                    }
//                }
//
//            } else {}
//        }
//    }
//    delete rgb;
//    delete pcm;
//    avformat_close_input(&ic);
    env->ReleaseStringUTFChars(url_, path);
 
}
 
 
unsigned char* readFileToByteArray(char* fileName, int* fsize) {
    FILE *f = fopen(fileName, "rb");
    fseek(f, 0, SEEK_END);
    *fsize = ftell(f);
    fseek(f, 0, SEEK_SET);
 
    unsigned char * string = (unsigned char*)malloc(*fsize);
    fread(string, *fsize, 1, f);
    fclose(f);
    return string;
 
}
 
void test () {
    int nSize1;
    char* sFile1;
    readFileToByteArray(sFile1,&nSize1);
}
 
 
#define MAXRECVSTRING 255  /* Longest string to receive */
 
void DieWithError(char *errorMessage) {
    printf("%s\n", errorMessage);
}  /* External error handling function */
 
#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), sendto(), and recvfrom() */
#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */
 
 
bool receiveBroadcastFirst = true;
 
int sock;
struct sockaddr_in broadcastAddr; /* Broadcast Address */
char recvString[MAXRECVSTRING+1]; /* Buffer for received string */
extern "C" JNIEXPORT jstring
JNICALL
Java_com_basic_security_utils_FaceId_receiveBroadcast(JNIEnv *env, jobject, jchar broadcastPort1) {                       /* Socket */
 
    unsigned short broadcastPort = broadcastPort1;     /* Port */
 
    int recvStringLen;                /* Length of received string */
 
    if (receiveBroadcastFirst) {
        /* Create a best-effort datagram socket using UDP */
        if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
            DieWithError("socket() failed");
 
        /* Construct bind structure */
        memset(&broadcastAddr, 0, sizeof(broadcastAddr));   /* Zero out structure */
        broadcastAddr.sin_family = AF_INET;                 /* Internet address family */
        broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY);  /* Any incoming interface */
        broadcastAddr.sin_port = htons(broadcastPort);      /* Broadcast port */
 
        /* Bind to the broadcast port */
        if (::bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) < 0)
            DieWithError("bind() failed");
        receiveBroadcastFirst = false;
    }
 
 
    /* Receive a single datagram from the server */
    if ((recvStringLen = recvfrom(sock, recvString, MAXRECVSTRING, 0, NULL, 0)) < 0)
        DieWithError("recvfrom() failed");
 
    recvString[recvStringLen] = '\0';
    printf("Received: %s\n", recvString);    /* Print the received string */
 
//    close(sock);
//    exit(0);
    return env->NewStringUTF(recvString);
 
}