camera_activity.cpp 13.3 KB
Newer Older
1
#include <dlfcn.h>
2 3 4
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
5
#include <android/log.h>
6
#include <cctype>
7 8
#include <string>
#include <vector>
9
#include <algorithm>
10
#include <opencv2/core/version.hpp>
11 12
#include "camera_activity.hpp"
#include "camera_wrapper.h"
13
#include "EngineCommon.h"
14

15 16 17 18 19 20 21
#undef LOG_TAG
#undef LOGE
#undef LOGD
#undef LOGI

#define LOG_TAG "OpenCV::camera"
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
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
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))

///////
// Debug
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>


using namespace std;

class CameraWrapperConnector
{
public:
    static CameraActivity::ErrorCode connect(int cameraId, CameraActivity* pCameraActivity, void** camera);
    static CameraActivity::ErrorCode disconnect(void** camera);
    static CameraActivity::ErrorCode setProperty(void* camera, int propIdx, double value);
    static CameraActivity::ErrorCode getProperty(void* camera, int propIdx, double* value);
    static CameraActivity::ErrorCode applyProperties(void** ppcamera);

    static void setPathLibFolder(const std::string& path);

private:
    static std::string pathLibFolder;
    static bool isConnectedToLib;

    static std::string getPathLibFolder();
50
    static std::string getDefaultPathLibFolder();
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    static CameraActivity::ErrorCode connectToLib();
    static CameraActivity::ErrorCode getSymbolFromLib(void * libHandle, const char* symbolName, void** ppSymbol);
    static void fillListWrapperLibs(const string& folderPath, vector<string>& listLibs);

    static InitCameraConnectC pInitCameraC;
    static CloseCameraConnectC pCloseCameraC;
    static GetCameraPropertyC pGetPropertyC;
    static SetCameraPropertyC pSetPropertyC;
    static ApplyCameraPropertiesC pApplyPropertiesC;

    friend bool nextFrame(void* buffer, size_t bufferSize, void* userData);
};

std::string CameraWrapperConnector::pathLibFolder;

66
bool CameraWrapperConnector::isConnectedToLib = false;
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
InitCameraConnectC  CameraWrapperConnector::pInitCameraC = 0;
CloseCameraConnectC  CameraWrapperConnector::pCloseCameraC = 0;
GetCameraPropertyC CameraWrapperConnector::pGetPropertyC = 0;
SetCameraPropertyC CameraWrapperConnector::pSetPropertyC = 0;
ApplyCameraPropertiesC CameraWrapperConnector::pApplyPropertiesC = 0;

#define INIT_CAMERA_SYMBOL_NAME "initCameraConnectC"
#define CLOSE_CAMERA_SYMBOL_NAME "closeCameraConnectC"
#define SET_CAMERA_PROPERTY_SYMBOL_NAME "setCameraPropertyC"
#define GET_CAMERA_PROPERTY_SYMBOL_NAME "getCameraPropertyC"
#define APPLY_CAMERA_PROPERTIES_SYMBOL_NAME "applyCameraPropertiesC"
#define PREFIX_CAMERA_WRAPPER_LIB "libnative_camera"


bool nextFrame(void* buffer, size_t bufferSize, void* userData)
{
    if (userData == NULL)
        return true;

    return ((CameraActivity*)userData)->onFrameBuffer(buffer, bufferSize);
}

CameraActivity::ErrorCode CameraWrapperConnector::connect(int cameraId, CameraActivity* pCameraActivity, void** camera)
{
    if (pCameraActivity == NULL)
    {
        LOGE("CameraWrapperConnector::connect error: wrong pointer to CameraActivity object");
        return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
    }

    CameraActivity::ErrorCode errcode=connectToLib();
    if (errcode) return errcode;

    void* cmr = (*pInitCameraC)((void*)nextFrame, cameraId, (void*)pCameraActivity);
    if (!cmr)
    {
        LOGE("CameraWrapperConnector::connectWrapper ERROR: the initializing function returned false");
        return CameraActivity::ERROR_CANNOT_INITIALIZE_CONNECTION;
    }

    *camera = cmr;
    return CameraActivity::NO_ERROR;
}

CameraActivity::ErrorCode CameraWrapperConnector::disconnect(void** camera)
{
    if (camera == NULL || *camera == NULL)
    {
        LOGE("CameraWrapperConnector::disconnect error: wrong pointer to camera object");
        return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
    }

    CameraActivity::ErrorCode errcode=connectToLib();
    if (errcode) return errcode;

    (*pCloseCameraC)(camera);

    return CameraActivity::NO_ERROR;
}

CameraActivity::ErrorCode CameraWrapperConnector::setProperty(void* camera, int propIdx, double value)
{
    if (camera == NULL)
    {
        LOGE("CameraWrapperConnector::setProperty error: wrong pointer to camera object");
        return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
    }

    (*pSetPropertyC)(camera, propIdx, value);

    return CameraActivity::NO_ERROR;
}

CameraActivity::ErrorCode CameraWrapperConnector::getProperty(void* camera, int propIdx, double* value)
{
    if (camera == NULL)
    {
        LOGE("CameraWrapperConnector::getProperty error: wrong pointer to camera object");
        return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
    }
147
    LOGE("calling (*pGetPropertyC)(%p, %d)", camera, propIdx);
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    *value = (*pGetPropertyC)(camera, propIdx);
    return CameraActivity::NO_ERROR;
}

CameraActivity::ErrorCode CameraWrapperConnector::applyProperties(void** ppcamera)
{
    if ((ppcamera == NULL) || (*ppcamera == NULL))
    {
        LOGE("CameraWrapperConnector::applyProperties error: wrong pointer to camera object");
        return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
    }

    (*pApplyPropertiesC)(ppcamera);
    return CameraActivity::NO_ERROR;
}

CameraActivity::ErrorCode CameraWrapperConnector::connectToLib()
{
    if (isConnectedToLib) {
        return CameraActivity::NO_ERROR;
    }

    dlerror();
171 172 173
    string folderPath = getPathLibFolder();
    if (folderPath.empty())
    {
174 175
        LOGD("Trying to find native camera in default OpenCV packages");
        folderPath = getDefaultPathLibFolder();
176 177
    }

178 179 180 181
    LOGD("CameraWrapperConnector::connectToLib: folderPath=%s", folderPath.c_str());

    vector<string> listLibs;
    fillListWrapperLibs(folderPath, listLibs);
182
    std::sort(listLibs.begin(), listLibs.end(), std::greater<string>());
183 184 185

    void * libHandle=0;
    string cur_path;
186
    for(size_t i = 0; i < listLibs.size(); i++) {
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
        cur_path=folderPath + listLibs[i];
        LOGD("try to load library '%s'", listLibs[i].c_str());
        libHandle=dlopen(cur_path.c_str(), RTLD_LAZY);
        if (libHandle) {
            LOGD("Loaded library '%s'", cur_path.c_str());
            break;
        } else {
            LOGD("CameraWrapperConnector::connectToLib ERROR: cannot dlopen camera wrapper library %s, dlerror=\"%s\"",
                 cur_path.c_str(), dlerror());
        }
    }

    if (!libHandle) {
        LOGE("CameraWrapperConnector::connectToLib ERROR: cannot dlopen camera wrapper library");
        return CameraActivity::ERROR_CANNOT_OPEN_CAMERA_WRAPPER_LIB;
    }

    InitCameraConnectC pInit_C;
    CloseCameraConnectC pClose_C;
    GetCameraPropertyC pGetProp_C;
    SetCameraPropertyC pSetProp_C;
    ApplyCameraPropertiesC pApplyProp_C;

    CameraActivity::ErrorCode res;

    res = getSymbolFromLib(libHandle, (const char*)INIT_CAMERA_SYMBOL_NAME, (void**)(&pInit_C));
    if (res) return res;

    res = getSymbolFromLib(libHandle, CLOSE_CAMERA_SYMBOL_NAME, (void**)(&pClose_C));
    if (res) return res;

    res = getSymbolFromLib(libHandle, GET_CAMERA_PROPERTY_SYMBOL_NAME, (void**)(&pGetProp_C));
    if (res) return res;

    res = getSymbolFromLib(libHandle, SET_CAMERA_PROPERTY_SYMBOL_NAME, (void**)(&pSetProp_C));
    if (res) return res;
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
    res = getSymbolFromLib(libHandle, APPLY_CAMERA_PROPERTIES_SYMBOL_NAME, (void**)(&pApplyProp_C));
    if (res) return res;

    pInitCameraC  = pInit_C;
    pCloseCameraC = pClose_C;
    pGetPropertyC = pGetProp_C;
    pSetPropertyC = pSetProp_C;
    pApplyPropertiesC = pApplyProp_C;
    isConnectedToLib=true;

    return CameraActivity::NO_ERROR;
}

CameraActivity::ErrorCode CameraWrapperConnector::getSymbolFromLib(void* libHandle, const char* symbolName, void** ppSymbol)
{
    dlerror();
    *(void **) (ppSymbol)=dlsym(libHandle, symbolName);

    const char* error_dlsym_init=dlerror();
    if (error_dlsym_init) {
        LOGE("CameraWrapperConnector::getSymbolFromLib ERROR: cannot get symbol of the function '%s' from the camera wrapper library, dlerror=\"%s\"",
             symbolName, error_dlsym_init);
        return CameraActivity::ERROR_CANNOT_GET_FUNCTION_FROM_CAMERA_WRAPPER_LIB;
    }
    return CameraActivity::NO_ERROR;
}

void CameraWrapperConnector::fillListWrapperLibs(const string& folderPath, vector<string>& listLibs)
{
    DIR *dp;
    struct dirent *ep;

    dp = opendir (folderPath.c_str());
    if (dp != NULL)
    {
259
        while ((ep = readdir (dp))) {
260 261 262 263 264 265 266 267 268 269
            const char* cur_name=ep->d_name;
            if (strstr(cur_name, PREFIX_CAMERA_WRAPPER_LIB)) {
                listLibs.push_back(cur_name);
                LOGE("||%s", cur_name);
            }
        }
        (void) closedir (dp);
    }
}

270 271
std::string CameraWrapperConnector::getDefaultPathLibFolder()
{
272
    #define BIN_PACKAGE_NAME(x) "org.opencv.lib_v" CVAUX_STR(CV_VERSION_EPOCH) CVAUX_STR(CV_VERSION_MAJOR) "_" x
273 274
    const char* const packageList[] = {BIN_PACKAGE_NAME("armv7a"), OPENCV_ENGINE_PACKAGE};
    for (size_t i = 0; i < sizeof(packageList)/sizeof(packageList[0]); i++)
275
    {
276
        char path[128];
277 278
        sprintf(path, "/data/data/%s/lib/", packageList[i]);
        LOGD("Trying package \"%s\" (\"%s\")", packageList[i], path);
279 280 281 282 283 284 285 286 287 288 289 290

        DIR* dir = opendir(path);
        if (!dir)
        {
            LOGD("Package not found");
            continue;
        }
        else
        {
            closedir(dir);
            return path;
        }
291 292 293 294 295
    }

    return string();
}

296 297 298 299 300 301 302 303 304 305 306
std::string CameraWrapperConnector::getPathLibFolder()
{
    if (!pathLibFolder.empty())
        return pathLibFolder;

    Dl_info dl_info;
    if(0 != dladdr((void *)nextFrame, &dl_info))
    {
        LOGD("Library name: %s", dl_info.dli_fname);
        LOGD("Library base address: %p", dl_info.dli_fbase);

307 308
        const char* libName=dl_info.dli_fname;
        while( ((*libName)=='/') || ((*libName)=='.') )
309
        libName++;
310

311 312 313 314 315
        char lineBuf[2048];
        FILE* file = fopen("/proc/self/smaps", "rt");

        if(file)
        {
316 317 318
            while (fgets(lineBuf, sizeof lineBuf, file) != NULL)
            {
                //verify that line ends with library name
319 320 321 322 323 324 325 326 327 328 329 330
                int lineLength = strlen(lineBuf);
                int libNameLength = strlen(libName);

                //trim end
                for(int i = lineLength - 1; i >= 0 && isspace(lineBuf[i]); --i)
                {
                    lineBuf[i] = 0;
                    --lineLength;
                }

                if (0 != strncmp(lineBuf + lineLength - libNameLength, libName, libNameLength))
                {
331
                //the line does not contain the library name
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
                    continue;
                }

                //extract path from smaps line
                char* pathBegin = strchr(lineBuf, '/');
                if (0 == pathBegin)
                {
                    LOGE("Strange error: could not find path beginning in lin \"%s\"", lineBuf);
                    continue;
                }

                char* pathEnd = strrchr(pathBegin, '/');
                pathEnd[1] = 0;

                LOGD("Libraries folder found: %s", pathBegin);

                fclose(file);
                return pathBegin;
350 351 352
            }
            fclose(file);
            LOGE("Could not find library path");
353 354 355
        }
        else
        {
356
            LOGE("Could not read /proc/self/smaps");
357 358 359 360
        }
    }
    else
    {
361
        LOGE("Could not get library name and base address");
362 363
    }

364
    return string();
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
}

void CameraWrapperConnector::setPathLibFolder(const string& path)
{
    pathLibFolder=path;
}


/////////////////////////////////////////////////////////////////////////////////////////////////

CameraActivity::CameraActivity() : camera(0), frameWidth(-1), frameHeight(-1)
{
}

CameraActivity::~CameraActivity()
{
    if (camera != 0)
        disconnect();
}

385
bool CameraActivity::onFrameBuffer(void* /*buffer*/, int /*bufferSize*/)
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
{
    LOGD("CameraActivity::onFrameBuffer - empty callback");
    return true;
}

void CameraActivity::disconnect()
{
    CameraWrapperConnector::disconnect(&camera);
}

bool CameraActivity::isConnected() const
{
    return camera != 0;
}

CameraActivity::ErrorCode CameraActivity::connect(int cameraId)
{
    ErrorCode rescode = CameraWrapperConnector::connect(cameraId, this, &camera);
    if (rescode) return rescode;

    return NO_ERROR;
}

double CameraActivity::getProperty(int propIdx)
{
    double propVal;
    ErrorCode rescode = CameraWrapperConnector::getProperty(camera, propIdx, &propVal);
    if (rescode) return -1;
    return propVal;
}

void CameraActivity::setProperty(int propIdx, double value)
{
    CameraWrapperConnector::setProperty(camera, propIdx, value);
}

void CameraActivity::applyProperties()
{
    frameWidth = -1;
    frameHeight = -1;
    CameraWrapperConnector::applyProperties(&camera);
427 428
    frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH);
    frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT);
429 430 431 432
}

int CameraActivity::getFrameWidth()
{
433
    if (frameWidth <= 0)
434
    frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH);
435
    return frameWidth;
436 437 438 439
}

int CameraActivity::getFrameHeight()
{
440
    if (frameHeight <= 0)
441
    frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT);
442
    return frameHeight;
443 444 445 446 447 448
}

void CameraActivity::setPathLibFolder(const char* path)
{
    CameraWrapperConnector::setPathLibFolder(path);
}