使用 vendor ndk 实现 Android Camera preview

3043次阅读  |  发布于2年以前

1.项目背景

2.vendor ndk和ndk接口的区别

2.1NDK 基础概念:

NDK 工具包中提供了完整的一套将 c/c++ 代码编译成静态/动态库的工具,而 Android.mk 和 Application.mk 你可以认为是描述编译参数和一些配置的文件。比如指定使用c++11还是c++14编译,会引用哪些共享库,并描述关系等,还会指定编译的ABI。只有有了这些 NDK 中的编译工具才能准确的编译 c/c++ 代码。

ABI(Application binary interface)应用程序二进制接口。不同的CPU 与指令集的每种组合都有定义的 ABI (应用程序二进制接口),一段程序只有遵循这个接口规范才能在该 CPU 上运行,所以同样的程序代码为了兼容多个不同的CPU,需要为不同的 ABI 构建不同的库文件。当然对于CPU来说,不同的架构并不意味着一定互不兼容。

armeabi设备只兼容armeabi;armeabi-v7a设备兼容armeabi-v7a、armeabi;arm64-v8a设备兼容arm64-v8a、armeabi-v7a、armeabi;X86设备兼容X86、armeabi;X86_64设备兼容X86_64、X86、armeabi;mips64设备兼容mips64、mips;mips只兼容mips;


Java Framework and JNI deference
画一个简单介绍通过NDK interface和Java framework SDK interface调用的区别,如果是使用Java framework就是直接使用Java SDK调用,在通过AIDL interface(binder 跨进程)调用到C framework,camera module is libcameraservice。直接调用底层是C/C++ framework的情况,只能通过 NDK在 Android中使用 JNI 与本地代码(如C、C++)交互。

2.2 Vendor NDk interface基本概念:

2.3为什么使用vendor NDK实现camera preview function

具体代码逻辑分析

一下为具体代码分析,提取的项目中的VNDK interface(和NDK interface都是相同的功能)主干,这些接口的具体使用可以在Google文档中查询,代码流程都是按照提供的sample借鉴的。
链接: camera2 API.

int mmi_cam_open_camera()
{
    /*open camera */
    mDeviceStateCallbacks.onDisconnected = camera_device_on_disconnected;
    mDeviceStateCallbacks.onError = camera_device_on_error;
    camera_status = ACameraManager_openCamera(
        cameraManager, mselectedCameraId, &mDeviceStateCallbacks, &mCameraDevice);
    if (camera_status != ACAMERA_OK) {
        MMI_ALOGE("Failed to open camera device (id: %s)", mselectedCameraId);
        return FAILED;
    }
    return SUCCESS;
}

    // Get frame from NDK camera
    camera_status_t camera_status = ACAMERA_ERROR_UNKNOWN;
    media_status_t media_status = AMEDIA_OK;
    cameraManager = ACameraManager_create();
    camera_status = ACameraManager_getCameraIdList(cameraManager, &mcameraIdList);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to get camera id list (reason: %d)", camera_status);
        return FAILED;
    }
    // The camera id has been converted to a number, 0,1,2, etc
    if(cam_id < 0 || cam_id >= mcameraIdList->numCameras) {
        MMI_ALOGE("Invalid camera index: %d\n", cam_id);
        return FAILED;
    }
    num_cameras = mcameraIdList->numCameras;
    mselectedCameraId = mcameraIdList->cameraIds[cam_id];
    camera_status = ACameraManager_getCameraCharacteristics(
        cameraManager, mselectedCameraId, &mcameraMetadata);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to get camera meta data of ID:%s", mselectedCameraId);
        return FAILED;
    }
    if(mmi_cam_open_camera() != SUCCESS) {
        MMI_ALOGE("fail to open camera \n");
        return FAILED;
    }
    camera_status = ACameraDevice_createCaptureRequest(
        mCameraDevice, TEMPLATE_PREVIEW, &mCaptureRequest);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to create preview capture request (id: %s)",
            mselectedCameraId);
        return FAILED;
    }
    // 获取AE的设置property,camera property一般是先get再set,避免直接set出现很多参数为0,效果不正常
    ACameraMetadata_const_entry entry;
    camera_status = ACaptureRequest_getConstEntry(
        mCaptureRequest, ACAMERA_CONTROL_AE_MODE, &entry);
    //先建立container,再往container里面放image reader(相当于显示图像的窗口)
    ACaptureSessionOutputContainer_create(&mCaptureSessionOutputContainer);
    AImageReader_new(preview_dim.width, preview_dim.height, AIMAGE_FORMAT_YUV_420_888, MAX_BUF_COUNT, &mImageReader);
    static AImageReader_ImageListener listener{
        //context赋值的是class的this指针,result上来可以解析出是谁下发的request。
        .context = this,
        .onImageAvailable = OnImageCallback,
    };
    //创建listener对是否有image的到来做出反应处理。
    media_status = AImageReader_setImageListener(mImageReader, &listener);
    if (media_status != AMEDIA_OK) {
        ALOGE(" Failed to set image listener");
        return FAILED;
    }
    media_status = AImageReader_getWindow(mImageReader, &mImgReaderAnw);
    if (media_status != AMEDIA_OK) {
        ALOGE(" Failed to get image reader native window");
        return FAILED;
    }
    camera_status = ACaptureSessionOutput_create(mImgReaderAnw, &mSessionOutput);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to create mSessionOutput, camera_status %d", camera_status);
        return FAILED;
    }
    camera_status = ACaptureSessionOutputContainer_add(
        mCaptureSessionOutputContainer, mSessionOutput);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to add mSessionOutput in mCaptureSessionOutputContainer, "
              "camera_status %d",
            camera_status);
        return FAILED;
    }
    camera_status = ACameraOutputTarget_create(mImgReaderAnw, &mCameraOutputTarget);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to create mCameraOutputTarget, camera_status %d",
            camera_status);
        return FAILED;
    }
    camera_status = ACaptureRequest_addTarget(mCaptureRequest, mCameraOutputTarget);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to add mCameraOutputTarget in mCaptureRequest, camera_status "
              "%d",
            camera_status);
        return FAILED;
    }
    camera_status = ACameraDevice_createCaptureSession(
        mCameraDevice, mCaptureSessionOutputContainer,
        &mCaptureSessionStateCallbacks, &mCaptureSession);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to create mCaptureSession by CameraDevice, camera_status %d",
            camera_status);
        return FAILED;
    }
    int previewSeqId;
    //当程序执行setRepeatingRequest之后camera service就不断的下发request,直到去stop
    camera_status = ACameraCaptureSession_setRepeatingRequest(
        mCaptureSession, NULL, 1, &mCaptureRequest, &previewSeqId);
    if (camera_status != ACAMERA_OK) {
        ALOGE(" Failed to setRepeatingRequest by mCaptureSession, camera_status %d",
            camera_status);
        return FAILED;
    }
//当camera HAL处理完buffer之后通过camera service callback image interface
static void OnImageCallback(AImageReader* reader)
{
    ImageCallback(ctx, reader);
}
void ImageCallback(void* context, AImageReader *reader)
{
    if (reader == nullptr) {
        ALOGE(" FaceAuth::ImageCallback AImageReader is null");
        return;
    }
    media_status_t status;
    AImage* image = nullptr;
    //image中存放指向数据buffer指针
    status = AImageReader_acquireNextImage(reader, &image);
    if (status != AMEDIA_OK) {
        ALOGE(" FaceAuth::ImageCallback Failed to get image");
        return;
    }
    mmi_cam_display_buffer(image);
    AImage_delete(image);
}

void mmi_cam_display_buffer(AImage* image)
{
    int preview_width = preview_dim.width;
    int preview_height = preview_dim.height;
    int preview_pixels = preview_width * preview_height;
    int rotation = sensor_mount_angle;
    int yPlaneIndex = 0;
    int uvPlaneIndex = 1;
    int yPlaneLength, cbcrLength;
    IMAGE_UV_DATA stYUVData;
    int32_t yrowStride = 0;
    int32_t uvrowStride = 0;
    int32_t format = 0;
    media_status = AImage_getFormat(image, &format);
    media_status = AImage_getPlaneRowStride(image, yPlaneIndex, &yrowStride);
    media_status = AImage_getPlaneRowStride(image, yPlaneIndex, &uvrowStride);
    media_status = AImage_getPlaneData(image, yPlaneIndex, &stYUVData.yPlanedataPtr, &yPlaneLength);
    media_status = AImage_getPlaneData(image, uvPlaneIndex, &stYUVData.cbDataPtr, &cbcrLength);
    if (media_status != AMEDIA_OK) {
        ALOGE("Failed to image get Plane Data (reason: %d)", media_status);
    }
    yPlaneLength, cbcrLength, preview_width, preview_height);
    for(int i=0; i<yPlaneLength; i+=yrowStride){
        memcpy(g_pPreview_Y, (uint8_t *) stYUVData.yPlanedataPtr, preview_width);
        stYUVData.yPlanedataPtr += yrowStride;
        g_pPreview_Y += preview_width;
    }
    g_pPreview_Y -= preview_pixels;
    for(int i=0; i<cbcrLength; i+=uvrowStride){
        memcpy(g_pPreview_UV, (uint8_t *) stYUVData.cbDataPtr, preview_width);
        stYUVData.cbDataPtr += uvrowStride;
        g_pPreview_UV += preview_width;
    }
    g_pPreview_UV -= preview_pixels / 2;
    yuvtorgb8888(preview_width, preview_height, g_pPreview_Y, g_pPreview_UV, g_pPreviewRGB8888);
}

对代码总体做一个介绍:

CSDN的代码预览没有高亮真的很难看,推荐copy到IDE中观看!

system和vendor分区binder进程间通信

Camera preview由VNDK interface组成的主体就如上一节的code所示,但是当时运行成功之后,在HAL中也能够看到request下发成功,但是怎么都无法接收到result的buffer回调,几乎折腾了一周都不知道为什么。

最后通过头给我查看发现是因为跨system和vendor分区binder通信的问题,provider进程的消息无法传输到fastmmi进程中,因为fastmmi的负责人根本没有考虑会有binder通信的问题。

#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/ProcessState.h>
//binder code
android::ProcessState::self()->startThreadPool();

在启动由VNDK interface组成的camera preview功能主进程中,main函数执行最后加入binder code。startThreadPool创建新的binder线程,通过单例模式保证一个进程只有一个线程池。然后调用thread::run方法调用threadloop,进一步调用到joinThreadPool函数循环不断地执行收到消息指令。

通过在主进程中建立binder通信就可以与provider进程进行交互,camera HAL传输buffer到camera service进而call back回调到fastmmi进程中。

具体binder通信可以看这个小哥写的博客,写得非常的不错!链接: 彻底理解Android Binder通信架构**.**

Acknowledge

原文链接: https://blog.csdn.net/chinamaoge/article/details/122394759

-- END --

Copyright© 2013-2019

京ICP备2023019179号-2