【camera 008】android camera id 注册、状态监控等状态变化 全流程梳理

1 应用层

1.1 应用侧 获取可用的camera id 列表

frameworks/base/core/java/android/hardware/camera2/CameraManager.java

java 复制代码
/**
     * Return the list of currently connected camera devices by identifier, including
     * cameras that may be in use by other camera API clients.
     *
     * <p>Non-removable cameras use integers starting at 0 for their
     * identifiers, while removable cameras have a unique identifier for each
     * individual device, even if they are the same model.</p>
     *
     * <p>This list doesn't contain physical cameras that can only be used as part of a logical
     * multi-camera device.</p>
     *
     * @return The list of currently connected camera devices.
     */
    @NonNull
    public String[] getCameraIdList() throws CameraAccessException {
        return CameraManagerGlobal.get().getCameraIdList();
    }

1.2 状态监控注册

APP 通过 registerAvailabilityCallback() 注册相机可用性回调:

frameworks/base/core/java/android/hardware/camera2/CameraManager.java

java 复制代码
/**
     * Register a callback to be notified about camera device availability.
     *
     * <p>Registering the same callback again will replace the handler with the
     * new one provided.</p>
     *
     * <p>The first time a callback is registered, it is immediately called
     * with the availability status of all currently known camera devices.</p>
     *
     * <p>{@link AvailabilityCallback#onCameraUnavailable(String)} will be called whenever a camera
     * device is opened by any camera API client. As of API level 23, other camera API clients may
     * still be able to open such a camera device, evicting the existing client if they have higher
     * priority than the existing client of a camera device. See open() for more details.</p>
     *
     * <p>Since this callback will be registered with the camera service, remember to unregister it
     * once it is no longer needed; otherwise the callback will continue to receive events
     * indefinitely and it may prevent other resources from being released. Specifically, the
     * callbacks will be invoked independently of the general activity lifecycle and independently
     * of the state of individual CameraManager instances.</p>
     *
     * @param callback the new callback to send camera availability notices to
     * @param handler The handler on which the callback should be invoked, or {@code null} to use
     *             the current thread's {@link android.os.Looper looper}.
     *
     * @throws IllegalArgumentException if the handler is {@code null} but the current thread has
     *             no looper.
     */
    public void registerAvailabilityCallback(@NonNull AvailabilityCallback callback,
            @Nullable Handler handler) {
        CameraManagerGlobal.get().registerAvailabilityCallback(callback,
                CameraDeviceImpl.checkAndWrapHandler(handler));
    }

1.3 状态变更接收

StateCallback

frameworks/base/core/java/android/hardware/camera2/CameraDevice.java

java 复制代码
/**
     * A callback objects for receiving updates about the state of a camera device.
     *
     * <p>A callback instance must be provided to the {@link CameraManager#openCamera} method to
     * open a camera device.</p>
     *
     * <p>These state updates include notifications about the device completing startup (
     * allowing for {@link #createCaptureSession} to be called), about device
     * disconnection or closure, and about unexpected device errors.</p>
     *
     * <p>Events about the progress of specific {@link CaptureRequest CaptureRequests} are provided
     * through a {@link CameraCaptureSession.CaptureCallback} given to the
     * {@link CameraCaptureSession#capture}, {@link CameraCaptureSession#captureBurst},
     * {@link CameraCaptureSession#setRepeatingRequest}, or
     * {@link CameraCaptureSession#setRepeatingBurst} methods.
     *
     * @see CameraManager#openCamera
     */
    public static abstract class StateCallback {
       /**
         * An error code that can be reported by {@link #onError}
         * indicating that the camera device is in use already.
         *
         * <p>
         * This error can be produced when opening the camera fails due to the camera
        *  being used by a higher-priority camera API client.
         * </p>
         *
         * @see #onError
         */
        public static final int ERROR_CAMERA_IN_USE = 1;

camera 报错类型

frameworks/base/core/java/android/hardware/camera2/CameraDevice.java

onError

frameworks/base/core/java/android/hardware/camera2/CameraDevice.java

java 复制代码
/**
     * A callback objects for receiving updates about the state of a camera device.
     *
     * <p>A callback instance must be provided to the {@link CameraManager#openCamera} method to
     * open a camera device.</p>
     *
     * <p>These state updates include notifications about the device completing startup (
     * allowing for {@link #createCaptureSession} to be called), about device
     * disconnection or closure, and about unexpected device errors.</p>
     *
     * <p>Events about the progress of specific {@link CaptureRequest CaptureRequests} are provided
     * through a {@link CameraCaptureSession.CaptureCallback} given to the
     * {@link CameraCaptureSession#capture}, {@link CameraCaptureSession#captureBurst},
     * {@link CameraCaptureSession#setRepeatingRequest}, or
     * {@link CameraCaptureSession#setRepeatingBurst} methods.
     *
     * @see CameraManager#openCamera
     */
    public static abstract class StateCallback {
       /**
         * An error code that can be reported by {@link #onError}
         * indicating that the camera device is in use already.
         *
         * <p>
         * This error can be produced when opening the camera fails due to the camera
        *  being used by a higher-priority camera API client.
         * </p>
         *
         * @see #onError
         */
        public static final int ERROR_CAMERA_IN_USE = 1;

        /**
         * An error code that can be reported by {@link #onError}
         * indicating that the camera device could not be opened
         * because there are too many other open camera devices.
         *
         * <p>
         * The system-wide limit for number of open cameras has been reached,
         * and more camera devices cannot be opened until previous instances are
         * closed.
         * </p>
         *
         * <p>
         * This error can be produced when opening the camera fails.
         * </p>
         *
         * @see #onError
         */
        public static final int ERROR_MAX_CAMERAS_IN_USE = 2;

        /**
         * An error code that can be reported by {@link #onError}
         * indicating that the camera device could not be opened due to a device
         * policy.
         *
         * @see android.app.admin.DevicePolicyManager#setCameraDisabled(android.content.ComponentName, boolean)
         * @see #onError
         */
        public static final int ERROR_CAMERA_DISABLED = 3;

       /**
         * An error code that can be reported by {@link #onError}
         * indicating that the camera device has encountered a fatal error.
         *
         * <p>The camera device needs to be re-opened to be used again.</p>
         *
         * @see #onError
         */
        public static final int ERROR_CAMERA_DEVICE = 4;

        /**
         * An error code that can be reported by {@link #onError}
         * indicating that the camera service has encountered a fatal error.
         *
         * <p>The Android device may need to be shut down and restarted to restore
         * camera function, or there may be a persistent hardware problem.</p>
         *
         * <p>An attempt at recovery <i>may</i> be possible by closing the
         * CameraDevice and the CameraManager, and trying to acquire all resources
         * again from scratch.</p>
         *
         * @see #onError
         */
        public static final int ERROR_CAMERA_SERVICE = 5;

        /** @hide */
        @Retention(RetentionPolicy.SOURCE)
        @IntDef(prefix = {"ERROR_"}, value =
            {ERROR_CAMERA_IN_USE,
             ERROR_MAX_CAMERAS_IN_USE,
             ERROR_CAMERA_DISABLED,
             ERROR_CAMERA_DEVICE,
             ERROR_CAMERA_SERVICE })
        public @interface ErrorCode {};
        
        ......
        
        /**
         * The method called when a camera device has encountered a serious error.
         *
         * <p>This callback may be called instead of {@link #onOpened}
         * if opening the camera fails.</p>
         *
         * <p>This indicates a failure of the camera device or camera service in
         * some way. Any attempt to call methods on this CameraDevice in the
         * future will throw a {@link CameraAccessException} with the
         * {@link CameraAccessException#CAMERA_ERROR CAMERA_ERROR} reason.
         * </p>
         *
         * <p>There may still be capture completion or camera stream callbacks
         * that will be called after this error is received.</p>
         *
         * <p>You should clean up the camera with {@link CameraDevice#close} after
         * this happens. Further attempts at recovery are error-code specific.</p>
         *
         * @param camera The device reporting the error
         * @param error The error code.
         *
         * @see #ERROR_CAMERA_IN_USE
         * @see #ERROR_MAX_CAMERAS_IN_USE
         * @see #ERROR_CAMERA_DISABLED
         * @see #ERROR_CAMERA_DEVICE
         * @see #ERROR_CAMERA_SERVICE
         */
        public abstract void onError(@NonNull CameraDevice camera,
                @ErrorCode int error); // Must implement
    }
        

2 framework CameraService

2.1 Camera ID 的注册与枚举

CameraService 启动时通过 enumerateProviders() 枚举系统中所有 Camera Provider:

frameworks/av/services/camera/libcameraservice/CameraService.h

java 复制代码
// Eumerate all camera providers in the system
    status_t enumerateProviders();
// Add/remove a new camera to camera and torch state lists or remove an unplugged one
    // Caller must not hold mServiceLock
    void addStates(const String8 id);
    void removeStates(const String8 id);

enumerateProviders() 遍历所有已注册的 Camera Provider,调用每个 Provider 的 getCameraIdList() 获取设备列表,然后通过 addStates() 将每个 Camera ID 添加到服务端的相机状态列表和闪光灯状态列表中。

frameworks/av/services/camera/libcameraservice/CameraService.cpp

java 复制代码
status_t CameraService::enumerateProviders() {
    status_t res;

    std::vector<std::string> deviceIds;
    {
        Mutex::Autolock l(mServiceLock);

        if (nullptr == mCameraProviderManager.get()) {
            mCameraProviderManager = new CameraProviderManager();
            res = mCameraProviderManager->initialize(this);
            if (res != OK) {
                ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
                        __FUNCTION__, strerror(-res), res);
                logServiceError(String8::format("Unable to initialize camera provider manager"),
                ERROR_DISCONNECTED);
                return res;
            }
        }


        // Setup vendor tags before we call get_camera_info the first time
        // because HAL might need to setup static vendor keys in get_camera_info
        // TODO: maybe put this into CameraProviderManager::initialize()?
        mCameraProviderManager->setUpVendorTags();

        if (nullptr == mFlashlight.get()) {
            mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
        }

        res = mFlashlight->findFlashUnits();
        if (res != OK) {
            ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
        }

        deviceIds = mCameraProviderManager->getCameraDeviceIds();
    }


    for (auto& cameraId : deviceIds) {
        String8 id8 = String8(cameraId.c_str());
        if (getCameraState(id8) == nullptr) {
            onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
        }
    }

    // Derive primary rear/front cameras, and filter their charactierstics.
    // This needs to be done after all cameras are enumerated and camera ids are sorted.
    if (SessionConfigurationUtils::IS_PERF_CLASS) {
        // Assume internal cameras are advertised from the same
        // provider. If multiple providers are registered at different time,
        // and each provider contains multiple internal color cameras, the current
        // logic may filter the characteristics of more than one front/rear color
        // cameras.
        Mutex::Autolock l(mServiceLock);
        filterSPerfClassCharacteristicsLocked();
    }

    return OK;
}

onDeviceStatusChanged

java 复制代码
void CameraService::onDeviceStatusChanged(const String8& id,
        CameraDeviceStatus newHalStatus) {
    ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
            id.string(), newHalStatus);

    StatusInternal newStatus = mapToInternal(newHalStatus);

    std::shared_ptr<CameraState> state = getCameraState(id);

    if (state == nullptr) {
        if (newStatus == StatusInternal::PRESENT) {
            ALOGI("%s: Unknown camera ID %s, a new camera is added",
                    __FUNCTION__, id.string());

            // First add as absent to make sure clients are notified below
            addStates(id);

            updateStatus(newStatus, id);
        } else {
            ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
        }
        return;
    }

    StatusInternal oldStatus = state->getStatus();

    if (oldStatus == newStatus) {
        ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
        return;
    }

    if (newStatus == StatusInternal::NOT_PRESENT) {
        logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
                newStatus));

        // Set the device status to NOT_PRESENT, clients will no longer be able to connect
        // to this device until the status changes
        updateStatus(StatusInternal::NOT_PRESENT, id);

        sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
        {
            // Don't do this in updateStatus to avoid deadlock over mServiceLock
            Mutex::Autolock lock(mServiceLock);

            // Remove cached shim parameters
            state->setShimParams(CameraParameters());

            // Remove online as well as offline client from the list of active clients,
            // if they are present
            clientToDisconnectOnline = removeClientLocked(id);
            clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
        }

        disconnectClient(id, clientToDisconnectOnline);
        disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);

        removeStates(id);
    } else {
        if (oldStatus == StatusInternal::NOT_PRESENT) {
            logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
                    newStatus));
        }
        updateStatus(newStatus, id);
    }
}

demo log

CameraProviderManager 中的 ID 映射

CameraProviderManager 维护 Camera ID 到 Provider 的映射关系:

frameworks/av/services/camera/libcameraservice/common/CameraProviderManager.h

cpp 复制代码
// Mapping from CameraDevice IDs to CameraProviders.
std::unordered_map<std::string, std::shared_ptr<HalCameraProvider>> mTorchProviderByCameraId;
std::mutex mProviderInterfaceMapLock;

每个 ProviderInfo 包含 DeviceInfo 列表,其中 DeviceInfo 保存了设备的 mId(ID 部分)和 mName(完整实例名)。

对于逻辑多摄,DeviceInfo 还包含物理摄像头 ID 列表:

cpp 复制代码
struct DeviceInfo {
    const std::string mName;       // Full instance name
    const std::string mId;         // ID section of full name
    bool mIsLogicalCamera;         // 是否为逻辑相机
    std::vector<std::string> mPhysicalIds;  // 物理相机ID列表
    CameraDeviceStatus mStatus;    // 设备状态
    // ...
};

ICameraServiceListener 接口定义

CameraService 通过 ICameraServiceListener AIDL 接口向客户端通知状态变化,关键回调包括:

cpp 复制代码
// frameworks/av/camera/aidl/android/hardware/ICameraServiceListener.aidl
void onStatusChanged(int status, String cameraId);
void onPhysicalCameraStatusChanged(int status, String cameraId, String physicalCameraId);
void onCameraOpened(String cameraId, String clientPackageName);
void onCameraClosed(String cameraId);
void onTorchStatusChanged(int status, String cameraId);
void onTorchStrengthLevelChanged(String cameraId, int newStrengthLevel);

CameraState 管理

每个 Camera ID 对应一个 CameraState 对象,封装了该相机的 ID、状态和资源成本:

CameraService 内部通过 mCameraStates 映射维护所有 Camera ID 到 CameraState 的对应关系。

cpp 复制代码
// CameraService.h
class CameraState {
public:
    String8 getId() const;
private:
    const String8 mId;          // Camera ID
    StatusInternal mStatus;     // 当前状态(PRESENT/NOT_PRESENT/ENUMERATING等)
    const int mCost;            // 资源成本
    std::set<String8> mConflicting;  // 互斥的相机ID集合
    mutable Mutex mStatusLock;
};

2.3 状态监控与更新 updateStatus

Camera 状态变化时,通过 CameraState::updateStatus() 进行状态机转换:

cpp 复制代码
template<class Func>
void CameraService::CameraState::updateStatus(StatusInternal status, const String8& cameraId,
        std::initializer_list<StatusInternal> rejectSourceStates, Func onStatusUpdatedLocked) {
    Mutex::Autolock lock(mStatusLock);
    StatusInternal oldStatus = mStatus;
    mStatus = status;
    if (oldStatus == status) return;

    // 状态转换合法性检查
    if (oldStatus == StatusInternal::NOT_PRESENT &&
        (status != StatusInternal::PRESENT && status != StatusInternal::ENUMERATING)) {
        mStatus = oldStatus;
        return;
    }
    // ...
    onStatusUpdatedLocked(cameraId, status);
}

状态转换后,通过 onStatusChanged() 通知所有已注册的 ICameraServiceListener。

2.4 状态通知分发

CameraService 将状态变化分发给所有监听器:

cpp 复制代码
// CameraService.cpp
void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
        std::initializer_list<StatusInternal> rejectSourceStates) {
    // Do not lock mServiceLock here or can get into a deadlock from
    // connect() -> disconnect -> updateStatus
    ......
    listener->getListener()->onStatusChanged(mapToInterface(status), String16(cameraId));

同时,Camera 的打开/关闭状态也通过独立回调通知:

cpp 复制代码
void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
        const String16& clientPackageName) {
    Mutex::Autolock lock(mStatusListenerLock);
    for (const auto& it : mListenerList) {
        // ...
        it->getListener()->onCameraOpened(cameraId64, clientPackageName);
        // 或
        it->getListener()->onCameraClosed(cameraId64);
    }
}
相关推荐
全方位办公软件1 小时前
Windows音频服务架构解析:AudioSrv与AudioEndpointBuilder排障
windows·命令行·powershell·音频服务·驱动修复·mmdevices·audiosrv
恋猫de小郭2 小时前
iOS for Web ,把原生 iOS App 跑到进浏览器里面,倒反天罡
android·前端·ios
思想觉悟3 小时前
Android启动流程之点rc文件
android·linux·面试
_祝你今天愉快13 小时前
Android 高级绘制:[四] Canvas-实际案例操作
android
三少爷的鞋14 小时前
Android 工程师的技术信仰崩塌史
android
AirDroid_cn16 小时前
Android 15 权限回溯:已授予的麦克风权限如何批量回收?
android
Mr_万能胶17 小时前
官方发布,不烧心的 AOSP 编译提速技巧
android·ci/cd·架构
booboosui17 小时前
安卓 8.1 也能装了:代价是一条黄字和两个静默 bug
android
Ehtan_Zheng20 小时前
Jetpack AppState Transform:让 Compose 的响应式状态走出 UI 层
android