初次授权后相机不显示图像
============

#### 问题现象

初次授权后相机不显示图像，重启应用后生效。

#### 背景知识

*   相机开发模型为Surface模型，该模型主要通过Surface实现数据交互。在开发相机应用界面时，首先需要通过创建[XComponent](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-xcomponent)组件为预览流提供Surface，再通过获取[XComponent](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-xcomponent)组件对应Surface的ID创建预览流，预览流画面即可直接在[XComponent](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-xcomponent)组件内渲染。
*   [PermissionRequestResult](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-permissionrequestresult)：此次权限申请的结果。
*   authResults：相应请求权限的结果。
    *   \-1：未授权。dialogShownResults返回为true，表示用户首次申请；dialogShownResults返回为false，表示权限已设置，无需弹窗，需要用户在"设置"中修改。
    *   0：已授权。
    *   2：未授权，表示请求无效。

#### 问题定位

1.  在HiLog日志中搜索XComponent发现应用通过native初始化了相机的预览画面。
    
    21:46:12.532   10809-10809   C03931/com.exa...AceXcomponent  com.example.hm  I     \[(100000:100000:scope)\] XComponent\[previewWindow\] native OnSurfaceCreated
    
2.  根据日志时间发现XComponent初始化时机早于授权弹窗。
    
    21:46:12.764   11213-11213   A05612/commonUI/ASP             com.huawe...commonUI  I     \[SPC\]\[PermissionDialog\]\[ViewModel\]: group: CAMERA, title: 允许“demo”访问你的相机？, reason: 拍照.
    

#### 分析结论

由于XComponent加载native实现的时机早于系统授权弹窗，导致相机初始化未完成，导致预览画面无法显示。

#### 修改建议

在初次授权时，重新调用相机的初始化流程。可以通过授权返回结果中dialogShownResults的值是否为true，判断当前是否是初次授权弹窗状态。

getPermission(permissions: Permissions\[\]): Promise<boolean> {
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
  let context: Context = this.uiContext.getHostContext() as common.UIAbilityContext;
  return new Promise((resolve) => {
    atManager.requestPermissionsFromUser(context, permissions,
      (err: BusinessError, data: PermissionRequestResult) => {
        if (err) {
          console.log(\`previewstreamsdemotest requestPermissionsFromUser fail, err->${JSON.stringify(err)}\`);
          return resolve(false);
        } else {
          console.info('PermissionRequestResult data:' + JSON.stringify(data));
          if (data.authResults\[0\] != 0) {
            return resolve(false);
          }


        _  // 第一次授权时候切换通道_
          if (data.dialogShownResults !== undefined &&
            data.dialogShownResults\[0\] === true &&
            data.authResults\[0\] === 0) {
            console.info('previewstreamsdemotest 已切换摄像头通道');
            this.PreviewCamera.switchChannel();
            this.channelId = this.PreviewCamera.GETCHANNELID();
            this.channelWidth = this.PreviewCamera.GETCHANNELWIDTH();
            this.channelHeight = this.PreviewCamera.GETCHANNELHEIGHT();
          }
          return resolve(true);
        }
      });
  });
}

*   初次授权时的打印结果，authResults结果为0，dialogShownResults结果为true：
    
    PermissionRequestResult data:{"permissions":\["ohos.permission.CAMERA"\],"authResults":\[0\],"dialogShownResults":\[true\]}
    
*   初次拒绝授权时的打印结果，authResults结果为-1，dialogShownResults结果为true：
    
    PermissionRequestResult data:{"permissions":\["ohos.permission.CAMERA"\],"authResults":\[-1\],"dialogShownResults":\[true\]}
    
*   授权后重启应用的打印结果，authResults结果为0，dialogShownResults结果为false：
    
    PermissionRequestResult data:{"permissions":\["ohos.permission.CAMERA"\],"authResults":\[0\],"dialogShownResults":\[false\]}
    

完整代码示例如下：

*   Index.d.ts导出文件：
    
    export const add: (a: number, b: number) => number;
    export const switchChannel: () => void;
    export  const GETCHANNELID: () => number;
    export const GETCHANNELWIDTH: () => number;
    export const GETCHANNELHEIGHT: () => number;
    
*   ArkTS侧实现：
    
    import abilityAccessCtrl, { Context, PermissionRequestResult, Permissions } from '@ohos.abilityAccessCtrl';
    import { BusinessError } from '@ohos.base';
    import common from '@ohos.app.ability.common';
    import camera from '@ohos.multimedia.camera';
    
    
    @Entry
    @Component
    struct Index {
      previewController: XComponentController = new XComponentController;
      photoController: XComponentController = new XComponentController;
      surfaceId: string = '';
      isUserAgent: boolean = false;
      uiContext = this.getUIContext();
      @State channelId: number = 0;
      @State channelWidth: number = 480;
      @State channelHeight: number = 480;
      pixelMap: PixelMap | undefined = undefined;
      photoOutput: camera.PhotoOutput | undefined = undefined;
      private PreviewCamera: ESObject;
      private isAuthorized: boolean = false;
    
    
      getPermission(permissions: Permissions\[\]): Promise<boolean> {
        let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
        let context: Context = this.uiContext.getHostContext() as common.UIAbilityContext;
        return new Promise((resolve) => {
          atManager.requestPermissionsFromUser(context, permissions,
            (err: BusinessError, data: PermissionRequestResult) => {
              if (err) {
                console.log(\`previewstreamsdemotest requestPermissionsFromUser fail, err->${JSON.stringify(err)}\`);
                return resolve(false);
              } else {
                console.info('PermissionRequestResult data:' + JSON.stringify(data));
                if (data.authResults\[0\] != 0) {
                  return resolve(false);
                }
    
    
              _  // 第一次授权时候切换通道_
                if (data.dialogShownResults !== undefined &&
                  data.dialogShownResults\[0\] === true &&
                  data.authResults\[0\] === 0) {
                  console.info('previewstreamsdemotest 已切换摄像头通道');
                  this.PreviewCamera.switchChannel();
                  this.channelId = this.PreviewCamera.GETCHANNELID();
                  this.channelWidth = this.PreviewCamera.GETCHANNELWIDTH();
                  this.channelHeight = this.PreviewCamera.GETCHANNELHEIGHT();
                }
                return resolve(true);
              }
            });
        });
      }
    
    
    
    
      aboutToAppear(): void {
       _ //user\_grant用户授权_
        this.getPermission(\['ohos.permission.CAMERA'\]).then(async (res) => {
          if (!res) {
            this.isAuthorized = false;
            let context = this.uiContext.getHostContext() as common.UIAbilityContext;
            context.startAbility({
              bundleName: 'com.huawei.hmos.settings',
              abilityName: 'com.huawei.hmos.settings.MainAbility',
              uri: 'application\_info\_entry', //application\_settings application\_info\_entry systemui\_notification\_settings
              parameters: {
                pushParams: 'com.example.previewstreamsdemo'
              }
            });
            return;
          }
          this.isAuthorized = true;
        });
      }
    
    
      aboutToDisappear(): void {
      }
    
    
      build() {
        Column() {
          XComponent({
            id: 'previewWindow',
            type: XComponentType.SURFACE,
            libraryname: 'entry',
            controller: this.previewController,
          })
            .onLoad((es: ESObject) => {
              this.PreviewCamera = es;
              let a: SurfaceRect = {
                offsetX: 10, _// X 偏移量_
                offsetY: 20, _// Y 偏移量_
                surfaceWidth: 1080, _// Surface 宽度_
                surfaceHeight: 1440 _// Surface 高度//_
              };
              this.previewController.setXComponentSurfaceRect(a);
              console.info('sf test XComponent has been inited');
            })
            .width('1080px')
            .height('1440px');
    
    
          Button('切换摄像头通道').onClick(() => {
            console.info('已切换摄像头通道');
            if (this.isAuthorized) {
              this.PreviewCamera.switchChannel();
              this.channelId = this.PreviewCamera.GETCHANNELID();
              this.channelWidth = this.PreviewCamera.GETCHANNELWIDTH();
              this.channelHeight = this.PreviewCamera.GETCHANNELHEIGHT();
              let a = this.previewController.getXComponentSurfaceRect();
              console.info('sf test' + a.surfaceWidth.toString());
            }
    
    
          });
          Text('通道:' + this.channelId);
          Text('通道像素宽度:' + this.channelWidth);
          Text('通道像素高度:' + this.channelHeight);
        }.justifyContent(FlexAlign.SpaceAround)
        .height('100%')
        .width('100%');
      }
    }
    
*   C/C++侧实现：
    *   napi\_init.cpp:
        
        /\*
         \* Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
         \*/
        #include <stdio.h>
        #include <stdlib.h>
        #include <ace/xcomponent/native\_interface\_xcomponent.h>
        #include "napi/native\_api.h"
        #include "hilog/log.h"
        #include "camera.h"
        
        
        #undef LOG\_DOMAIN
        #undef LOG\_TAG
        #define LOG\_DOMAIN 0x3200 _// 全局domain宏，标识业务领域_
        #define LOG\_TAG "MY\_TAG"  _// 全局tag宏，标识模块日志tag_
        
        NDKCamera \*g\_camera;
        
        
        static napi\_value Add(napi\_env env, napi\_callback\_info info)
        {
            size\_t argc = 2;
            napi\_value args\[2\] = {nullptr};
        
        
            napi\_get\_cb\_info(env, info, &argc, args, nullptr, nullptr);
        
        
            napi\_valuetype valuetype0;
            napi\_typeof(env, args\[0\], &valuetype0);
        
        
            napi\_valuetype valuetype1;
            napi\_typeof(env, args\[1\], &valuetype1);
        
        
            double value0;
            napi\_get\_value\_double(env, args\[0\], &value0);
        
        
            double value1;
            napi\_get\_value\_double(env, args\[1\], &value1);
        
        
            napi\_value sum;
            napi\_create\_double(env, value0 + value1, &sum);
        
        
            return sum;
        }
        
        
        static napi\_value switchChannel(napi\_env env, napi\_callback\_info info)
        {
            if (g\_camera == nullptr) {
                g\_camera = NDKCamera::GetInstance();
                if (g\_camera == nullptr) {
                    return nullptr;
                }
            }
            g\_camera->SwitchPreviewChannel();
            return nullptr;
        }
        
        
        static napi\_value GETCHANNELID(napi\_env env, napi\_callback\_info info)
        {
            napi\_value napi\_id;
            int32\_t id;
            if (g\_camera == nullptr) {
                g\_camera = NDKCamera::GetInstance();
                if (g\_camera == nullptr) {
                    return nullptr;
                }
            }
            id = g\_camera->GETCHANNELID();
            if (napi\_ok != napi\_create\_int32(env, id, &napi\_id)) {
                OH\_LOG\_ERROR(LOG\_APP, "GETCHANNELID:napi\_create\_int32 failed");
                return nullptr;
            }
        
        
            return napi\_id;
        }
        
        
        static napi\_value GETCHANNELWIDTH(napi\_env env, napi\_callback\_info info)
        {
            napi\_value napi\_width;
            int32\_t width;
            if (g\_camera == nullptr) {
                g\_camera = NDKCamera::GetInstance();
                if (g\_camera == nullptr) {
                    return nullptr;
                }
            }
            width = g\_camera->GETCHANNELWIDTH();
            if (napi\_ok != napi\_create\_int32(env, width, &napi\_width)) {
                OH\_LOG\_ERROR(LOG\_APP, "GETCHANNELWIDTH:napi\_create\_int32 failed");
                return nullptr;
            }
        
        
            return napi\_width;
        }
        
        
        static napi\_value GETCHANNELHEIGHT(napi\_env env, napi\_callback\_info info)
        {
            napi\_value napi\_height;
            int32\_t height;
            if (g\_camera == nullptr) {
                g\_camera = NDKCamera::GetInstance();
                if (g\_camera == nullptr) {
                    return nullptr;
                }
            }
            height = g\_camera->GETCHANNELHEIGHT();
            if (napi\_ok != napi\_create\_int32(env, height, &napi\_height)) {
                OH\_LOG\_ERROR(LOG\_APP, "GETCHANNELHEIGHT:napi\_create\_int32 failed");
                return nullptr;
            }
        
        
            return napi\_height;
        }
        
        
        EXTERN\_C\_START
        static napi\_value Init(napi\_env env, napi\_value exports)
        {
            napi\_property\_descriptor desc\[\] = {
                {"add", nullptr, Add, nullptr, nullptr, nullptr, napi\_default, nullptr},
                {"switchChannel", nullptr, switchChannel, nullptr, nullptr, nullptr, napi\_default, nullptr},
                {"GETCHANNELID", nullptr, GETCHANNELID, nullptr, nullptr, nullptr, napi\_default, nullptr},
                {"GETCHANNELWIDTH", nullptr, GETCHANNELWIDTH, nullptr, nullptr, nullptr, napi\_default, nullptr},
                {"GETCHANNELHEIGHT", nullptr, GETCHANNELHEIGHT, nullptr, nullptr, nullptr, napi\_default, nullptr},
            };
            napi\_define\_properties(env, exports, sizeof(desc) / sizeof(desc\[0\]), desc);
        
        
            napi\_value exportInstance = nullptr;
           _ // 用来解析出被wrap了NativeXComponent指针的属性_
            napi\_get\_named\_property(env, exports, OH\_NATIVE\_XCOMPONENT\_OBJ, &exportInstance);
            OH\_NativeXComponent \*nativeXComponent = nullptr;
         _   // 通过napi\_unwrap接口，解析出NativeXComponent的实例指针_
            napi\_unwrap(env, exportInstance, reinterpret\_cast<void \*\*>(&nativeXComponent));
           _ // 获取XComponentId_
            char idStr\[OH\_XCOMPONENT\_ID\_LEN\_MAX + 1\] = {};
            uint64\_t idSize = OH\_XCOMPONENT\_ID\_LEN\_MAX + 1;
            OH\_NativeXComponent\_GetXComponentId(nativeXComponent, idStr, &idSize);
        
        
            OH\_NativeXComponent\_Callback \*callback = new OH\_NativeXComponent\_Callback();
            callback->OnSurfaceCreated = OnSurfaceCreatedCB;
            callback->OnSurfaceChanged = OnSurfaceChangedCB;
            callback->OnSurfaceDestroyed = OnSurfaceDestroyedCB;
            callback->DispatchTouchEvent = DispatchTouchEventCB;
        
        
          _  // 注册回调函数_
            OH\_NativeXComponent\_RegisterCallback(nativeXComponent, callback);
            g\_camera = NDKCamera::GetInstance();
            return exports;
        }
        EXTERN\_C\_END
        
        
        static napi\_module demoModule = {
            .nm\_version = 1,
            .nm\_flags = 0,
            .nm\_filename = nullptr,
            .nm\_register\_func = Init,
            .nm\_modname = "entry",
            .nm\_priv = ((void \*)0),
            .reserved = {0},
        };
        
        
        extern "C" \_\_attribute\_\_((constructor)) void RegisterEntryModule(void) { napi\_module\_register(&demoModule); }
        
    *   camera.cpp:
        
        /\*
         \* Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
         \*/
        #include <cstdint>
        #include <cstring>
        #include <sstream>
        #include <sys/mman.h>
        #include <accesstoken/ability\_access\_control.h>
        #include "hilog/log.h"
        #include "camera.h"
        
        
        #undef LOG\_DOMAIN
        #undef LOG\_TAG
        #define LOG\_DOMAIN 0x3200 _// 全局domain宏，标识业务领域_
        #define LOG\_TAG "MY\_TAG" _ // 全局tag宏，标识模块日志tag_
        
        OHNativeWindow \*g\_nativeWindow = nullptr;
        
        
        void CaptureSessionOnFocusStateChange(Camera\_CaptureSession \*session, Camera\_FocusState focusState)
        {
            OH\_LOG\_INFO(LOG\_APP, "CaptureSessionOnFocusStateChange");
        }
        
        
        void CaptureSessionOnError(Camera\_CaptureSession \*session, Camera\_ErrorCode errorCode)
        {
            OH\_LOG\_INFO(LOG\_APP, "CaptureSessionOnError = %{public}d", errorCode);
        }
        
        
        CaptureSession\_Callbacks \*GetCaptureSessionRegister(void)
        {
            static CaptureSession\_Callbacks captureSessionCallbacks = {.onFocusStateChange = CaptureSessionOnFocusStateChange,
                                                                       .onError = CaptureSessionOnError};
            return &captureSessionCallbacks;
        }
        
        
        void PreviewOutputOnFrameStart(Camera\_PreviewOutput \*previewOutput)
        {
            OH\_LOG\_INFO(LOG\_APP, "PreviewOutputOnFrameStart");
        }
        
        
        void PreviewOutputOnFrameEnd(Camera\_PreviewOutput \*previewOutput, int32\_t frameCount)
        {
            OH\_LOG\_INFO(LOG\_APP, "PreviewOutputOnFrameEnd = %{public}d", frameCount);
        }
        
        
        void PreviewOutputOnError(Camera\_PreviewOutput \*previewOutput, Camera\_ErrorCode errorCode)
        {
            OH\_LOG\_INFO(LOG\_APP, "PreviewOutputOnError = %{public}d", errorCode);
        }
        
        
        PreviewOutput\_Callbacks \*GetPreviewOutputListener(void)
        {
            static PreviewOutput\_Callbacks previewOutputListener = {.onFrameStart = PreviewOutputOnFrameStart,
                                                                    .onFrameEnd = PreviewOutputOnFrameEnd,
                                                                    .onError = PreviewOutputOnError};
            return &previewOutputListener;
        }
        
        
        void OnCameraInputError(const Camera\_Input \*cameraInput, Camera\_ErrorCode errorCode)
        {
            OH\_LOG\_INFO(LOG\_APP, "OnCameraInput errorCode = %{public}d", errorCode);
        }
        
        
        CameraInput\_Callbacks \*GetCameraInputListener(void)
        {
            static CameraInput\_Callbacks cameraInputCallbacks = {.onError = OnCameraInputError};
            return &cameraInputCallbacks;
        }
        
        
        void CameraManagerStatusCallback(Camera\_Manager \*cameraManager, Camera\_StatusInfo \*status)
        {
            OH\_LOG\_INFO(LOG\_APP, "CameraManagerStatusCallback is called");
        }
        
        
        CameraManager\_Callbacks \*GetCameraManagerListener()
        {
            static CameraManager\_Callbacks cameraManagerListener = {.onCameraStatus = CameraManagerStatusCallback};
            return &cameraManagerListener;
        }
        
        _// YUV到RGB的转换公式_
        int YUV2RGBA(unsigned char y, unsigned char u, unsigned char v)
        {
            unsigned char r = 0;
            unsigned char g = 0;
            unsigned char b = 0;
        
            r = (unsigned char)(y + 1.4075 \* (v - 128));
            g = (unsigned char)(y - 0.34455 \* (u - 128) - 0.7169 \* (v - 128));
            b = (unsigned char)(y + 1.779 \* (u - 128));
        
        
           _ // 构建RGBA整数值_
            return (0xff << 24) | (int)(r << 16) | (int)(g << 8) | (int)b;
        }
        
        _// 将YUV420数据转换为RGBA整数值_
        void YUV420ToRGBAInt(unsigned char \*src, int \*dst, int width, int height, int stride)
        {
            unsigned char \*pY = src;
            unsigned char \*pU = src + width \* height;
        
        
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    unsigned char u = pU\[(y / 2) \* width + (x / 2) \* 2\];
                    unsigned char v = pU\[(y / 2) \* width + (x / 2) \* 2 + 1\];
                    dst\[y \* stride + x\] = YUV2RGBA(pY\[y \* width + x\], u, v);
                }
            }
        }
        
        
        static void OnCallback(OH\_ImageReceiverNative \*receiver)
        {
            int32\_t yStride, uStride, vStride, sWidth, sHeight;
        
        
            _// 读取 OH\_ImageReceiverNative 的下一个图片对象_
            OH\_ImageNative \*image = nullptr;
            OH\_ImageReceiverNative\_ReadNextImage(receiver, &image);
        
        
           _ // 读取 OH\_ImageNative 的 size 属性_
            Image\_Size size;
            OH\_ImageNative\_GetImageSize(image, &size);
            sWidth = size.width;
            sHeight = size.height;
            OH\_LOG\_ERROR(LOG\_APP, "size \[%{public}s\]:\[%{public}u\],sWidth \[%{public}d\],sHeight \[%{public}d\]", \_\_FUNCTION\_\_,
                         \_\_LINE\_\_, sWidth, sHeight);
        
          _  // 读取 OH\_ImageNative 的组件列表的元素个数。_
            size\_t componentTypeSize = 0;
            OH\_ImageNative\_GetComponentTypes(image, nullptr, &componentTypeSize);
        
        
         _   // 读取 OH\_ImageNative 的组件列表。_
            uint32\_t \*componentTypes = new uint32\_t\[componentTypeSize\];
            OH\_ImageNative\_GetComponentTypes(image, &componentTypes, &componentTypeSize);
        
        
            uint32\_t component = componentTypes\[0\];
        
        
            _// 读取 OH\_ImageNative 的第一个组件所对应的缓冲区对象。_
            OH\_NativeBuffer \*nativeBuffer = nullptr;
            OH\_ImageNative\_GetByteBuffer(image, component, &nativeBuffer);
        
        
            OH\_ImageNative\_GetRowStride(image, component, &yStride);
            uStride = yStride;
            vStride = yStride;
        
        
            void \*srcVir = nullptr;
            OH\_NativeBuffer\_Map(nativeBuffer, &srcVir);
            uint8\_t \*srcBuffer = static\_cast<uint8\_t \*>(srcVir);
        
        
            if (yStride != size.width) {
              _  // 传给其他支持stride的接口处理，或去除stride数据_
                _// 去除stride数据示例:将byteBuffer中的数据去除stride，拷贝得到新的dstBuffer数据_
                size\_t dstBufferSize = size.width \* size.height \* 1.5; _// 相机预览流返回NV21格式_
                std::unique\_ptr<uint8\_t\[\]> dstBuffer = std::make\_unique<uint8\_t\[\]>(dstBufferSize);
                uint8\_t \*dstPtr = dstBuffer.get();
                for (int j = 0; j < size.height \* 1.5; j++) {
                    std::copy\_n(static\_cast<const uint8\_t\*>(srcBuffer), size.width, static\_cast<uint8\_t\*>(dstPtr));
                    dstPtr += size.width;
                    srcBuffer += yStride;
                }
                srcBuffer = dstBuffer.get();
            }
        
        
            OH\_LOG\_ERROR(LOG\_APP, "local \[%{public}s\]:\[%{public}u\],sWidth \[%{public}d\],yStride \[%{public}d\]", \_\_FUNCTION\_\_,
                         \_\_LINE\_\_, sWidth, yStride);
        
        
            OHNativeWindow \*nativeWindow;
            OH\_LOG\_ERROR(LOG\_APP, "local \[%{public}s\]:\[%{public}u\], \[%{public}p\]", \_\_FUNCTION\_\_, \_\_LINE\_\_, g\_nativeWindow);
        
        
           _ // 设置 OHNativeWindowBuffer 的宽高_
            int32\_t code = SET\_BUFFER\_GEOMETRY;
            _// 这里的nativeWindow是从上一步骤中的回调函数中获得的_
            int32\_t ret = OH\_NativeWindow\_NativeWindowHandleOpt(g\_nativeWindow, code, sWidth, sHeight);
        
            code = GET\_BUFFER\_GEOMETRY;
            int32\_t h, w;
            _// 这里的nativeWindow是从上一步骤中的回调函数中获得的_
            ret = OH\_NativeWindow\_NativeWindowHandleOpt(g\_nativeWindow, code, &h, &w);
            OH\_LOG\_ERROR(LOG\_APP, "local H W\[%{public}s\]:\[%{public}u\], \[%{public}d\]  \[%{public}d\]", \_\_FUNCTION\_\_, \_\_LINE\_\_, h,
                         w);
        
        
            code = SET\_TRANSFORM;
            int32\_t transform = NATIVEBUFFER\_ROTATE\_270;
            ret = OH\_NativeWindow\_NativeWindowHandleOpt(g\_nativeWindow, code, transform);
        
            OHNativeWindowBuffer \*buffer = nullptr;
            int releaseFenceFd = -1;
           _ // 通过 OH\_NativeWindow\_NativeWindowRequestBuffer 获取 OHNativeWindowBuffer 实例_
            ret = OH\_NativeWindow\_NativeWindowRequestBuffer(g\_nativeWindow, &buffer, &releaseFenceFd);
            if (ret != 0 || buffer == nullptr) {
                return;
            }
           _ // 通过 OH\_NativeWindow\_GetBufferHandleFromNative 获取 buffer 的 handle_
            BufferHandle \*bufferHandle = OH\_NativeWindow\_GetBufferHandleFromNative(buffer);
           _ // 使用系统接口mmap将bufferHandle对应的共享内存映射到用户空间，可以通过映射出来的虚拟地址向bufferHandle中写入图像数据_
            _// bufferHandle->virAddr是bufferHandle在共享内存中的起始地址，bufferHandle->size是bufferHandle在共享内存中的内存占用大小_
            void \*mappedAddr =
                mmap(bufferHandle->virAddr, (bufferHandle->size), PROT\_READ | PROT\_WRITE, MAP\_SHARED, bufferHandle->fd, 0);
            if (mappedAddr == MAP\_FAILED) {
                return;
            }
        
        
            OH\_LOG\_ERROR(LOG\_APP, "local size \[%{public}s\]:\[%{public}u\], \[%{public}d\]", \_\_FUNCTION\_\_, \_\_LINE\_\_,
                         (bufferHandle->size));
        
        
            YUV420ToRGBAInt(srcBuffer, (int \*)mappedAddr, sWidth, sHeight, bufferHandle->stride / 4);
        
        
           _ // 设置刷新区域，如果Region中的Rect为nullptr,或者rectNumber为0，则认为OHNativeWindowBuffer全部有内容更改。_
            Region region{nullptr, 0};
          _  // 通过OH\_NativeWindow\_NativeWindowFlushBuffer提交给消费者使用，例如：显示在屏幕上。_
            OH\_NativeWindow\_NativeWindowFlushBuffer(g\_nativeWindow, buffer, -1, region);
        
        
           _ // 内存使用完记得去掉内存映射_
            int result = munmap(mappedAddr, (bufferHandle->size));
            if (result == -1) {
                return;
            }
        
        
            OH\_NativeBuffer\_Unmap(nativeBuffer);
            int errCode = OH\_ImageNative\_Release(image);
            OH\_LOG\_ERROR(LOG\_APP, "zhulin local \[%{public}s\]:\[%{public}u\], \[%{public}d\] ok", \_\_FUNCTION\_\_, \_\_LINE\_\_, errCode);
        }
        NDKCamera \*g\_ndkCamera = nullptr;
        NDKCameraErrorCode NDKCamera::Init()
        {
            uint32\_t size = 0;
        
           _ // 创建CameraManager对象_
            Camera\_ErrorCode ret = OH\_Camera\_GetCameraManager(&\_cameraManager);
            if (\_cameraManager == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_Camera\_GetCameraMananger failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
           _ // 监听相机状态变化_
            ret = OH\_CameraManager\_RegisterCallback(\_cameraManager, GetCameraManagerListener());
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_RegisterCallback failed.");
                return ERROR\_FAILED;
            }
        
        
         _   // 获取相机列表_
            ret = OH\_CameraManager\_GetSupportedCameras(\_cameraManager, &\_cameras, &size);
            if (\_cameras == nullptr || size < 0 || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_GetSupportedCameras failed.");
                return ERROR\_FAILED;
            }
        
        
            for (int i = 0; i < size; i++) {
                OH\_LOG\_ERROR(
                    LOG\_APP,
                    "OH\_CameraManager\_GetSupportedCameras camera %{public}d.Pos: %{public}d,Type: %{public}d,Conn:  %{public}d",
                    i, \_cameras\[i\].cameraPosition, \_cameras\[i\].cameraType, \_cameras\[i\].connectionType);
            }
        
        
           _ // 创建相机输入流_
            ret = OH\_CameraManager\_CreateCameraInput(\_cameraManager, &\_cameras\[cameraDeviceIndex\], &\_cameraInput);
            if (\_cameraInput == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreateCameraInput failed.");
                return ERROR\_FAILED;
            }
        
        
          _  // 监听cameraInput错误信息_
            ret = OH\_CameraInput\_RegisterCallback(\_cameraInput, GetCameraInputListener());
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraInput\_RegisterCallback failed.");
                return ERROR\_FAILED;
            }
        
            _// 打开相机_
            ret = OH\_CameraInput\_Open(\_cameraInput);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraInput\_Open failed.");
                return ERROR\_FAILED;
            }
        
        
           _ // 获取相机设备支持的输出流能力_
            ret = OH\_CameraManager\_GetSupportedCameraOutputCapability(\_cameraManager, &\_cameras\[cameraDeviceIndex\],
                                                                      &\_cameraOutputCapability);
            if (\_cameraOutputCapability == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_GetSupportedCameraOutputCapability failed.");
                return ERROR\_FAILED;
            }
        
        
            uint32\_t cameraOrientitaion;
            ret = OH\_CameraDevice\_GetCameraOrientation(&\_cameras\[cameraDeviceIndex\], &cameraOrientitaion);
        
        
            if (\_cameraOutputCapability->previewProfilesSize < 0) {
                OH\_LOG\_ERROR(LOG\_APP, "previewProfilesSize == null");
                return ERROR\_FAILED;
            }
            for (int i = 0; i < \_cameraOutputCapability->previewProfilesSize; i++) {
                OH\_LOG\_INFO(LOG\_APP, "%{public}d: previewProfile width:%{public}d height:%{public}d format:%{public}d ", i,
                            \_cameraOutputCapability->previewProfiles\[i\]->size.width,
                            \_cameraOutputCapability->previewProfiles\[i\]->size.height,
                            \_cameraOutputCapability->previewProfiles\[i\]->format);
                if (CAMERA\_FORMAT\_YUV\_420\_SP == \_cameraOutputCapability->previewProfiles\[i\]->format) {
                    previewProfile = \_cameraOutputCapability->previewProfiles\[i\];
                }
            }
        
            for (int i = 0; i < \_cameraOutputCapability->photoProfilesSize; i++) {
                OH\_LOG\_INFO(LOG\_APP, "%{public}d: photoProfile width:%{public}d height:%{public}d format:%{public}d ", i,
                            \_cameraOutputCapability->photoProfiles\[i\]->size.width,
                            \_cameraOutputCapability->photoProfiles\[i\]->size.height,
                            \_cameraOutputCapability->photoProfiles\[i\]->format);
                if (CAMERA\_FORMAT\_YUV\_420\_SP == \_cameraOutputCapability->photoProfiles\[i\]->format) {
                    previewProfile = \_cameraOutputCapability->photoProfiles\[i\];
                }
            }
        
            previewProfile = \_cameraOutputCapability->previewProfiles\[previewProfileId\];
        
        
            if (\_cameraOutputCapability->photoProfilesSize < 0) {
                OH\_LOG\_ERROR(LOG\_APP, "photoProfilesSize == null");
            }
            \_photoProfile = \_cameraOutputCapability->photoProfiles\[photoProfileId\];
        
        
            Image\_ErrorCode ErrCode;
            Image\_Size imageSize = {previewProfile->size.width, previewProfile->size.height};
            ErrCode = OH\_ImageReceiverOptions\_Create(&\_options);
            if (IMAGE\_SUCCESS != ErrCode) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverOptions\_Create failed.ErrCode %{public}d", ErrCode);
                return ERROR\_FAILED;
            }
            OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverOptions\_Create success.options 0x%{public}p", \_options);
        
            ErrCode = OH\_ImageReceiverOptions\_SetSize(\_options, imageSize);
            if (IMAGE\_SUCCESS != ErrCode) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverOptions\_SetSize failed.ErrCode %{public}d", ErrCode);
                return ERROR\_FAILED;
            }
        
        
            ErrCode = OH\_ImageReceiverOptions\_SetCapacity(\_options, 8);
            if (IMAGE\_SUCCESS != ErrCode) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverOptions\_SetCapacity failed.ErrCode %{public}d", ErrCode);
            }
        
        
           _ // 读取 OH\_ImageReceiverOptions 的 capacity 属性_
            int32\_t capacity = 0;
            ErrCode = OH\_ImageReceiverOptions\_GetCapacity(\_options, &capacity);
            if (ErrCode != IMAGE\_SUCCESS) {
                OH\_LOG\_ERROR(LOG\_APP,
                             "ImageReceiverNativeCTest get image receiver options capacity failed, errCode: %{public}d.",
                             ErrCode);
                OH\_ImageReceiverOptions\_Release(\_options);
                return ERROR\_FAILED;
            }
        
            _// 检查读取到的 capacity 值是否为设定值_
            if (capacity != 8) {
                OH\_LOG\_ERROR(LOG\_APP,
                             "ImageReceiverNativeCTest get image receiver options capacity failed, capacity: %{public}d.",
                             capacity);
                OH\_ImageReceiverOptions\_Release(\_options);
                return ERROR\_FAILED;
            }
        
        
            ErrCode = OH\_ImageReceiverNative\_Create(\_options, &\_receiver);
            if (IMAGE\_SUCCESS != ErrCode) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverNative\_Create failed.ErrCode %{public}d", ErrCode);
            }
            OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverNative\_Create success.receiver 0x%{public}p", \_receiver);
        
        
            ErrCode = OH\_ImageReceiverNative\_On(\_receiver, OnCallback);
            if (ErrCode != IMAGE\_SUCCESS) {
                OH\_LOG\_ERROR(LOG\_APP, "ImageReceiverNativeCTest image receiver on failed, errCode: %{public}d.", ErrCode);
                OH\_ImageReceiverOptions\_Release(\_options);
                OH\_ImageReceiverNative\_Release(\_receiver);
                return ERROR\_FAILED;
            }
        
        
            ErrCode = OH\_ImageReceiverNative\_GetReceivingSurfaceId(\_receiver, &imageReceiverSurfaceId);
            if (ErrCode != IMAGE\_SUCCESS) {
                OH\_LOG\_ERROR(LOG\_APP,
                             "OH\_ImageReceiverNative\_GetReceivingSurfaceId image receiver on failed, errCode: %{public}d.",
                             ErrCode);
                OH\_ImageReceiverOptions\_Release(\_options);
                OH\_ImageReceiverNative\_Release(\_receiver);
                return ERROR\_FAILED;
            }
            OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverNative\_GetReceivingSurfaceId imageReceiverSurfaceId %{public}lu",
                         imageReceiverSurfaceId);
        
        
            std::ostringstream surfaceIDString;
            surfaceIDString << imageReceiverSurfaceId;
        
        
          _  // 创建预览输出流_
            ret = OH\_CameraManager\_CreatePreviewOutput(\_cameraManager, previewProfile, surfaceIDString.str().c\_str(),
                                                       &\_previewOutput);
            if (previewProfile == nullptr || \_previewOutput == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreatePreviewOutput failed.");
                return ERROR\_FAILED;
            } else {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreatePreviewOutput success.previewSurfaceId : %{public}s",
                             surfaceIDString.str().c\_str());
            }
        
        
           _ // 监听预览输出错误信息_
            ret = OH\_PreviewOutput\_RegisterCallback(\_previewOutput, GetPreviewOutputListener());
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_PreviewOutput\_RegisterCallback failed.");
                return ERROR\_FAILED;
            }
        
        
            _// 创建会话_
            ret = OH\_CameraManager\_CreateCaptureSession(\_cameraManager, &\_captureSession);
            if (\_captureSession == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreateCaptureSession failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
          _  // 监听session错误信息_
            ret = OH\_CaptureSession\_RegisterCallback(\_captureSession, GetCaptureSessionRegister());
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_RegisterCallback failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
          _  // 开始配置会话_
            ret = OH\_CaptureSession\_BeginConfig(\_captureSession);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_BeginConfig failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
            _// 向会话中添加相机输入流_
            ret = OH\_CaptureSession\_AddInput(\_captureSession, \_cameraInput);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_AddInput failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
         _   // 向会话中添加预览输出流_
            ret = OH\_CaptureSession\_AddPreviewOutput(\_captureSession, \_previewOutput);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_AddPreviewOutput failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
          _  // 提交会话配置_
            ret = OH\_CaptureSession\_CommitConfig(\_captureSession);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_CommitConfig failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
          _  // 启动会话_
            ret = OH\_CaptureSession\_Start(\_captureSession);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_Start failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
            return ERROR\_SUCCESS;
        }
        
        _// 定义回调函数_
        void OnSurfaceCreatedCB(OH\_NativeXComponent \*component, void \*window)
        {
           _ // 可获取 OHNativeWindow 实例_
            g\_nativeWindow = static\_cast<OHNativeWindow \*>(window);
            _// 此回调触发后，window默认引用计数会设置为1，若存在并发使用了window相关的接口和xcompnent析构的情况，_
            _// 则需要通过OH\_NativeWindow\_NativeObjectReference和OH\_NativeWindow\_NativeObjectUnreference对window进行_
            _// 手动引用计数加1和减1，防止xcomponent析构后，并发调用window相关接口触发野指针或空指针的崩溃。_
        }
        void OnSurfaceChangedCB(OH\_NativeXComponent \*component, void \*window)
        {
          _  // 可获取 OHNativeWindow 实例_
            g\_nativeWindow = static\_cast<OHNativeWindow \*>(window);
         _   // ..._
        }
        void OnSurfaceDestroyedCB(OH\_NativeXComponent \*component, void \*window)
        {
           _ // 可获取 OHNativeWindow 实例_
            OHNativeWindow \*nativeWindow = static\_cast<OHNativeWindow \*>(window);
           _ // 此回调触发后，会将window进行引用计数减1的操作，当window的应用计数为0后，会触发window的析构，_
            _// window析构后，不可再通过window进行接口调用，否则可能会触发野指针或空指针的崩溃。_
        }
        void DispatchTouchEventCB(OH\_NativeXComponent \*component, void \*window)
        {
           _ // 可获取 OHNativeWindow 实例_
            OHNativeWindow \*nativeWindow = static\_cast<OHNativeWindow \*>(window);
           _ // ..._
        }
        
        
        NDKCameraErrorCode NDKCamera::SwitchPreviewChannel()
        {
            Camera\_ErrorCode ret;
            Image\_ErrorCode ErrCode;
        
        
            if (NULL == \_cameraOutputCapability) {
                return ERROR\_FAILED;
            }
        
        
            if (\_cameraOutputCapability->previewProfilesSize < 0) {
                OH\_LOG\_ERROR(LOG\_APP, "previewProfilesSize == null");
                return ERROR\_FAILED;
            }
        
        
            previewProfileId = (previewProfileId + 1) % \_cameraOutputCapability->previewProfilesSize;
            previewProfile = \_cameraOutputCapability->previewProfiles\[previewProfileId\];
        
        
            if (NULL == \_options) {
                return ERROR\_FAILED;
            }
        
        
          _  // 创建相机输入流_
            ret = OH\_CameraManager\_CreateCameraInput(\_cameraManager, &\_cameras\[cameraDeviceIndex\], &\_cameraInput);
            if (\_cameraInput == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreateCameraInput failed.");
                return ERROR\_FAILED;
            }
        
            _// 监听cameraInput错误信息_
            ret = OH\_CameraInput\_RegisterCallback(\_cameraInput, GetCameraInputListener());
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraInput\_RegisterCallback failed.");
                return ERROR\_FAILED;
            }
        
        
           _ // 打开相机_
            ret = OH\_CameraInput\_Open(\_cameraInput);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraInput\_Open failed.");
                return ERROR\_FAILED;
            }
        
            Image\_Size imageSize = {previewProfile->size.width, previewProfile->size.height};
            ErrCode = OH\_ImageReceiverOptions\_SetSize(\_options, imageSize);
            if (IMAGE\_SUCCESS != ErrCode) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverOptions\_SetSize failed.ErrCode %{public}d", ErrCode);
                return ERROR\_FAILED;
            }
        
        
         _   // 释放之前创建的\_receiver_
            OH\_ImageReceiverNative\_Release(\_receiver);
        
        
           _ // 根据新的profile重新创建\_receiver_
            ErrCode = OH\_ImageReceiverNative\_Create(\_options, &\_receiver);
            if (IMAGE\_SUCCESS != ErrCode) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverNative\_Create failed.ErrCode %{public}d", ErrCode);
                return ERROR\_FAILED;
            }
            OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverNative\_Create success.receiver 0x%{public}p", \_receiver);
        
        
            ErrCode = OH\_ImageReceiverNative\_On(\_receiver, OnCallback);
            if (ErrCode != IMAGE\_SUCCESS) {
                OH\_LOG\_ERROR(LOG\_APP, "ImageReceiverNativeCTest image receiver on failed, errCode: %{public}d.", ErrCode);
                OH\_ImageReceiverOptions\_Release(\_options);
                OH\_ImageReceiverNative\_Release(\_receiver);
                return ERROR\_FAILED;
            }
        
        
            ErrCode = OH\_ImageReceiverNative\_GetReceivingSurfaceId(\_receiver, &imageReceiverSurfaceId);
            if (ErrCode != IMAGE\_SUCCESS) {
                OH\_LOG\_ERROR(LOG\_APP,
                             "OH\_ImageReceiverNative\_GetReceivingSurfaceId image receiver on failed, errCode: %{public}d.",
                             ErrCode);
                OH\_ImageReceiverOptions\_Release(\_options);
                OH\_ImageReceiverNative\_Release(\_receiver);
                return ERROR\_FAILED;
            }
            OH\_LOG\_ERROR(LOG\_APP, "OH\_ImageReceiverNative\_GetReceivingSurfaceId imageReceiverSurfaceId %{public}lu",
                         imageReceiverSurfaceId);
        
        
            std::ostringstream surfaceIDString;
            surfaceIDString << imageReceiverSurfaceId;
        
        
           _ // 创建预览输出流,其中参数 previewSurfaceId 参考上文 XComponent 组件，预览流为XComponent组件提供的surface_
            ret = OH\_CameraManager\_CreatePreviewOutput(\_cameraManager, previewProfile, surfaceIDString.str().c\_str(),
                                                       &\_previewOutput);
            if (previewProfile == nullptr || \_previewOutput == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreatePreviewOutput failed.");
                return ERROR\_FAILED;
            } else {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreatePreviewOutput success.previewSurfaceId : %{public}s",
                             surfaceIDString.str().c\_str());
            }
        
        
            _// 监听预览输出错误信息_
            ret = OH\_PreviewOutput\_RegisterCallback(\_previewOutput, GetPreviewOutputListener());
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_PreviewOutput\_RegisterCallback failed.");
                return ERROR\_FAILED;
            }
        
        
          _  // 创建会话_
            ret = OH\_CaptureSession\_Release(\_captureSession);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_Release failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
            ret = OH\_CameraManager\_CreateCaptureSession(\_cameraManager, &\_captureSession);
            if (\_captureSession == nullptr || ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CameraManager\_CreateCaptureSession failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
           _ // 监听session错误信息_
            ret = OH\_CaptureSession\_RegisterCallback(\_captureSession, GetCaptureSessionRegister());
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_RegisterCallback failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
            _// 开始配置会话_
            ret = OH\_CaptureSession\_BeginConfig(\_captureSession);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_BeginConfig failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
          _  // 向会话中添加相机输入流_
            ret = OH\_CaptureSession\_AddInput(\_captureSession, \_cameraInput);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_AddInput failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
         _   // 向会话中添加预览输出流_
            ret = OH\_CaptureSession\_AddPreviewOutput(\_captureSession, \_previewOutput);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_AddPreviewOutput failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
          _  // 提交会话配置_
            ret = OH\_CaptureSession\_CommitConfig(\_captureSession);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_CommitConfig failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
        
        
            _// 启动会话_
            ret = OH\_CaptureSession\_Start(\_captureSession);
            if (ret != CAMERA\_OK) {
                OH\_LOG\_ERROR(LOG\_APP, "OH\_CaptureSession\_Start failed.ret : %{public}d", ret);
                return ERROR\_FAILED;
            }
            return ERROR\_SUCCESS;
        }
        
        
        NDKCamera \*NDKCamera::GetInstance()
        {
            if (g\_ndkCamera == nullptr) {
                g\_ndkCamera = new NDKCamera();
            }
            if (g\_ndkCamera->Init() != ERROR\_SUCCESS) {
                return nullptr;
            }
            return g\_ndkCamera;
        }
        
        
        int NDKCamera::GETCHANNELID() { return previewProfileId; }
        
        
        int NDKCamera::GETCHANNELWIDTH() { return previewProfile->size.width; }
        
        
        int NDKCamera::GETCHANNELHEIGHT() { return previewProfile->size.height; }
        
        
        
        
        NDKCameraErrorCode NDKCamera::CheckSelfPermission()
        {
            if (!OH\_AT\_CheckSelfPermission(OHOS\_PERMISSION\_CAMERA)) {
                return ERROR\_FAILED;
            }
            return ERROR\_SUCCESS;
        }
        
    *   camera.h:
        
        /\*
         \* Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
         \*/
        #ifndef MYCAMERANATIVE\_CAMERA\_H
        #define MYCAMERANATIVE\_CAMERA\_H
        #include <multimedia/image\_framework/image/image\_receiver\_native.h>
        #include <ace/xcomponent/native\_interface\_xcomponent.h>
        #include "ohcamera/camera.h"
        #include "ohcamera/camera\_device.h"
        #include "ohcamera/camera\_input.h"
        #include "ohcamera/capture\_session.h"
        #include "ohcamera/photo\_output.h"
        #include "ohcamera/preview\_output.h"
        #include "ohcamera/video\_output.h"
        #include "ohcamera/camera\_manager.h"
        
        
        
        
        typedef enum NDKCameraErrorCode {
            ERROR\_SUCCESS = 0,
            ERROR\_FAILED,
        } NDKCameraErrorCode;
        
        
        #define OHOS\_PERMISSION\_CAMERA "ohos.permission.CAMERA"
        
        
        
        
        class NDKCamera {
        public:
            NDKCameraErrorCode SwitchPreviewChannel(); _// 切换摄像头通道_
            static NDKCameraErrorCode CheckSelfPermission();
            int GETCHANNELID();
            int GETCHANNELWIDTH();
            int GETCHANNELHEIGHT();
            static NDKCamera \* GetInstance();
        private:
            NDKCameraErrorCode Init();
            Camera\_Manager\* \_cameraManager = nullptr;
            Camera\_Device\* \_cameras = nullptr;
            Camera\_CaptureSession\* \_captureSession = nullptr;
            Camera\_OutputCapability\* \_cameraOutputCapability = nullptr;
            const Camera\_Profile\* previewProfile = nullptr;
            const Camera\_Profile\* \_photoProfile = nullptr;
            int previewProfileId = 0;
            int photoProfileId = 0;
            Camera\_PreviewOutput\* \_previewOutput = nullptr;
            Camera\_PhotoOutput\* \_photoOutput = nullptr;
            Camera\_Input\* \_cameraInput = nullptr;
            OH\_ImageReceiverOptions\* \_options = nullptr;
            OH\_ImageReceiverNative \* \_receiver = nullptr;
            uint64\_t imageReceiverSurfaceId = 0;
            uint32\_t cameraDeviceIndex = 0;
        };
        
        
        extern void OnSurfaceCreatedCB(OH\_NativeXComponent\* component, void\* window);
        extern void OnSurfaceChangedCB(OH\_NativeXComponent\* component, void\* window);
        extern void OnSurfaceDestroyedCB(OH\_NativeXComponent\* component, void\* window);
        extern void DispatchTouchEventCB(OH\_NativeXComponent\* component, void\* window);
        
        
        #endif _// MYCAMERANATIVE\_CAMERA\_H_
        
*   CMake编译脚本：
    
    \# the minimum version of CMake.
    cmake\_minimum\_required(VERSION 3.5)
    project(MyCameraNative)
    
    
    set(NATIVERENDER\_ROOT\_PATH ${CMAKE\_CURRENT\_SOURCE\_DIR})
    
    
    if(DEFINED PACKAGE\_FIND\_FILE)
        include(${PACKAGE\_FIND\_FILE})
    endif()
    
    
    include\_directories(${NATIVERENDER\_ROOT\_PATH}
                        ${NATIVERENDER\_ROOT\_PATH}/include)
    
    
    add\_library(entry SHARED napi\_init.cpp camera.cpp)
    target\_link\_libraries(entry PUBLIC libace\_napi.z.so)
    target\_link\_libraries(entry PUBLIC libohcamera.so
                                       libace\_ndk.z.so
                                       libhilog\_ndk.z.so
                                       libimage\_receiver.so
                                       libohimage.so
                                       libnative\_image.so
                                       libimage\_ndk.z.so
                                       libimage\_receiver\_ndk.z.so
                                       libnative\_buffer.so
                                       libnative\_window.so
                                       libability\_access\_control.so)