android - hardware

本文介绍了Android硬件抽象层(HAL)的基本结构和工作原理,包括核心数据结构hw_module_t和hw_device_t的定义,以及模块加载流程。还详细解释了像素格式和图像转换等概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
hardware.h
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef ANDROID_INCLUDE_HARDWARE_HARDWARE_H
#define ANDROID_INCLUDE_HARDWARE_HARDWARE_H

#include <stdint.h>
#include <sys/cdefs.h>

#include <cutils/native_handle.h>

__BEGIN_DECLS

/*
 * Value for the hw_module_t.tag field
 */

#define MAKE_TAG_CONSTANT(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D))

#define HARDWARE_MODULE_TAG MAKE_TAG_CONSTANT('H', 'W', 'M', 'T')
#define HARDWARE_DEVICE_TAG MAKE_TAG_CONSTANT('H', 'W', 'D', 'T')

struct hw_module_t;
struct hw_module_methods_t;
struct hw_device_t;

/**
 * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
 * and the fields of this data structure must begin with hw_module_t
 * followed by module specific information.
 */
typedef struct hw_module_t {
    /** tag must be initialized to HARDWARE_MODULE_TAG */
    uint32_t tag;

    /** major version number for the module */
    uint16_t version_major;

    /** minor version number of the module */
    uint16_t version_minor;

    /** Identifier of module */
    const char *id;

    /** Name of this module */
    const char *name;

    /** Author/owner/implementor of the module */
    const char *author;

    /** Modules methods */
    struct hw_module_methods_t* methods;

    /** module's dso */
    void* dso;

    /** padding to 128 bytes, reserved for future use */
    uint32_t reserved[32-7];

} hw_module_t;

typedef struct hw_module_methods_t {
    /** Open a specific device */
    int (*open)(const struct hw_module_t* module, const char* id,
            struct hw_device_t** device);

} hw_module_methods_t;

/**
 * Every device data structure must begin with hw_device_t
 * followed by module specific public methods and attributes.
 */
typedef struct hw_device_t {
    /** tag must be initialized to HARDWARE_DEVICE_TAG */
    uint32_t tag;

    /** version number for hw_device_t */
    uint32_t version;

    /** reference to the module this device belongs to */
    struct hw_module_t* module;

    /** padding reserved for future use */
    uint32_t reserved[12];

    /** Close this device */
    int (*close)(struct hw_device_t* device);

} hw_device_t;

/**
 * Name of the hal_module_info
 */
#define HAL_MODULE_INFO_SYM         HMI

/**
 * Name of the hal_module_info as a string
 */
#define HAL_MODULE_INFO_SYM_AS_STR  "HMI"

/**
 * Get the module info associated with a module by id.
 * @return: 0 == success, <0 == error and *pHmi == NULL
 */
int hw_get_module(const char *id, const struct hw_module_t **module);


/**
 * pixel format definitions
 */

enum {
    HAL_PIXEL_FORMAT_RGBA_8888    = 1,
    HAL_PIXEL_FORMAT_RGBX_8888    = 2,
    HAL_PIXEL_FORMAT_RGB_888      = 3,
    HAL_PIXEL_FORMAT_RGB_565      = 4,
    HAL_PIXEL_FORMAT_BGRA_8888    = 5,
    HAL_PIXEL_FORMAT_RGBA_5551    = 6,
    HAL_PIXEL_FORMAT_RGBA_4444    = 7,
    HAL_PIXEL_FORMAT_YCbCr_422_SP = 0x10,
    HAL_PIXEL_FORMAT_YCrCb_420_SP = 0x11,
    HAL_PIXEL_FORMAT_YCbCr_422_P  = 0x12,
    HAL_PIXEL_FORMAT_YCbCr_420_P  = 0x13,
    HAL_PIXEL_FORMAT_YCbCr_422_I  = 0x14,
    HAL_PIXEL_FORMAT_YCbCr_420_I  = 0x15,
    HAL_PIXEL_FORMAT_CbYCrY_422_I = 0x16,
    HAL_PIXEL_FORMAT_CbYCrY_420_I = 0x17,
    HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED = 0x20,
    HAL_PIXEL_FORMAT_YCbCr_420_SP       = 0x21,
    HAL_PIXEL_FORMAT_YCrCb_420_SP_TILED = 0x22,
    HAL_PIXEL_FORMAT_YCrCb_422_SP       = 0x23,
};


/**
 * Transformation definitions
 */

enum {
    /* flip source image horizontally */
    HAL_TRANSFORM_FLIP_H    = 0x01,
    /* flip source image vertically */
    HAL_TRANSFORM_FLIP_V    = 0x02,
    /* rotate source image 90 degrees */
    HAL_TRANSFORM_ROT_90    = 0x04,
    /* rotate source image 180 degrees */
    HAL_TRANSFORM_ROT_180   = 0x03,
    /* rotate source image 270 degrees */
    HAL_TRANSFORM_ROT_270   = 0x07,
};

__END_DECLS

#endif  /* ANDROID_INCLUDE_HARDWARE_HARDWARE_H */
 
 
hareware.c
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <hardware/hardware.h>

#include <cutils/properties.h>

#include <dlfcn.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <limits.h>

#define LOG_TAG "HAL"
#include <utils/Log.h>

/** Base path of the hal modules */
#define HAL_LIBRARY_PATH "/system/lib/hw"

/**
 * There are a set of variant filename for modules. The form of the filename
 * is "<MODULE_ID>.variant.so" so for the led module the Dream variants 
 * of base "ro.product.board", "ro.board.platform" and "ro.arch" would be:
 *
 * led.trout.so
 * led.msm7k.so
 * led.ARMV6.so
 * led.default.so
 */

static const char *variant_keys[] = {
    "ro.hardware",  /* This goes first so that it can pick up a different
                       file on the emulator. */
    "ro.product.board",
    "ro.board.platform",
    "ro.arch"
};

static const int HAL_VARIANT_KEYS_COUNT =
    (sizeof(variant_keys)/sizeof(variant_keys[0]));

/**
 * Load the file defined by the variant and if successful
 * return the dlopen handle and the hmi.
 * @return 0 = success, !0 = failure.
 */
static int load(const char *id,
        const char *path,
        const struct hw_module_t **pHmi)
{
    int status;
    void *handle;
    struct hw_module_t *hmi;

    /*
     * load the symbols resolving undefined symbols before
     * dlopen returns. Since RTLD_GLOBAL is not or'd in with
     * RTLD_NOW the external symbols will not be global
     */
    handle = dlopen(path, RTLD_NOW);
    if (handle == NULL) {
        char const *err_str = dlerror();
        LOGE("load: module=%s\n%s", path, err_str?err_str:"unknown");
        status = -EINVAL;
        goto done;
    }

    /* Get the address of the struct hal_module_info. */
    const char *sym = HAL_MODULE_INFO_SYM_AS_STR;
    hmi = (struct hw_module_t *)dlsym(handle, sym);
    if (hmi == NULL) {
        LOGE("load: couldn't find symbol %s", sym);
        status = -EINVAL;
        goto done;
    }

    /* Check that the id matches */
    if (strcmp(id, hmi->id) != 0) {
        LOGE("load: id=%s != hmi->id=%s", id, hmi->id);
        status = -EINVAL;
        goto done;
    }

    hmi->dso = handle;

    /* success */
    status = 0;

    done:
    if (status != 0) {
        hmi = NULL;
        if (handle != NULL) {
            dlclose(handle);
            handle = NULL;
        }
    } else {
        LOGV("loaded HAL id=%s path=%s hmi=%p handle=%p",
                id, path, *pHmi, handle);
    }

    *pHmi = hmi;

    return status;
}

int hw_get_module(const char *id, const struct hw_module_t **module) 
{
    int status;
    int i;
    const struct hw_module_t *hmi = NULL;
    char prop[PATH_MAX];
    char path[PATH_MAX];

    /*
     * Here we rely on the fact that calling dlopen multiple times on
     * the same .so will simply increment a refcount (and not load
     * a new copy of the library).
     * We also assume that dlopen() is thread-safe.
     */

    /* Loop through the configuration variants looking for a module */
    for (i=0 ; i<HAL_VARIANT_KEYS_COUNT+1 ; i++) {
        if (i < HAL_VARIANT_KEYS_COUNT) {
            if (property_get(variant_keys[i], prop, NULL) == 0) {
                continue;
            }
            snprintf(path, sizeof(path), "%s/%s.%s.so",
                    HAL_LIBRARY_PATH, id, prop);
        } else {
            snprintf(path, sizeof(path), "%s/%s.default.so",
                    HAL_LIBRARY_PATH, id);
        }
        if (access(path, R_OK)) {
            continue;
        }
        /* we found a library matching this id/variant */
        break;
    }

    status = -ENOENT;
    if (i < HAL_VARIANT_KEYS_COUNT+1) {
        /* load the module, if this fails, we're doomed, and we should not try
         * to load a different variant. */
        status = load(id, path, module);
    }

    return status;
}



 

2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W java.lang.IllegalArgumentException: CaptureRequest contains unconfigured Input/Output Surface! 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.hardware.camera2.CaptureRequest.convertSurfaceToStreamId(CaptureRequest.java:765) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.hardware.camera2.impl.CameraDeviceImpl.submitCaptureRequest(CameraDeviceImpl.java:1274) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.hardware.camera2.impl.CameraDeviceImpl.setRepeatingRequest(CameraDeviceImpl.java:1330) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.hardware.camera2.impl.CameraCaptureSessionImpl.setRepeatingRequest(CameraCaptureSessionImpl.java:314) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at com.tx.dms.demo.DmsActivity$27.onConfigured(DmsActivity.java:1771) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.hardware.camera2.impl.CallbackProxies$SessionStateCallbackProxy.lambda$onConfigured$0$android-hardware-camera2-impl-CallbackProxies$SessionStateCallbackProxy(CallbackProxies.java:53) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.hardware.camera2.impl.CallbackProxies$SessionStateCallbackProxy$$ExternalSyntheticLambda6.run(Unknown Source:4) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.os.Handler.handleCallback(Handler.java:942) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.os.Handler.dispatchMessage(Handler.java:99) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.os.Looper.loopOnce(Looper.java:201) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.os.Looper.loop(Looper.java:288) 2025-04-14 00:09:04.530 7452-7530 System.err com.tx.dms W at android.os.HandlerThread.run(HandlerThread.java:67)
最新发布
05-29
<think>好的,我现在需要解决用户在使用Camera2API时遇到的无法触发ImageReader.OnImageAvailableListener回调的问题,同时还要处理IllegalArgumentException:CaptureRequestcontains unconfiguredInput/Output Surface错误。让我仔细分析一下用户的问题和之前的对话,确保解决方案准确有效。首先,用户提到他们已经正确设置了预览,但无法进入ImageReader的回调。这可能意味着ImageReader没有被正确配置或者其Surface没有被添加到CaptureRequest中。此外,出现的IllegalArgumentException错误表明在创建CaptureRequest时,可能添加了未在CaptureSession中配置的Surface。回顾用户提供的代码,发现他们在创建CaptureSession时,surfaceList只包含了一个来自SurfaceTexture的Surface。而如果用户同时需要预览和ImageReader处理图像数据,应该将两者的Surface都添加到surfaceList中。例如,在用户代码中,如果mImageReader存在,它的Surface也需要被包含进去,并且在创建CaptureRequest.Builder时,也需要将这两个Surface都添加为target。在用户提供的startCaptureSession方法中,他们在创建surfaceList时,仅处理了mSurfaceTexture的情况,而没有处理mImageReader的情况。这可能导致ImageReader的Surface没有被添加到CaptureSession的配置中,从而导致后续的CaptureRequest尝试使用未配置的Surface,引发IllegalArgumentException错误。接下来,我需要验证是否正确地将ImageReader的Surface添加到了CaptureSession的配置中。根据Camera2 API的工作流程,所有在CaptureRequest中使用的Surface都必须在创建CaptureSession时被包含在surfaceList参数中。如果漏掉了ImageReader的Surface,就会导致后续的请求中包含未配置的Surface,从而抛出异常。 因此,解决方案应该是将ImageReader的Surface和预览的Surface都添加到surfaceList中,并且在创建CaptureRequest.Builder时,同时将它们作为目标。这需要修改用户代码中的surfaceList构建部分,以及mPreviewRequestBuilder的addTarget调用。 此外,用户可能没有正确初始化ImageReader,例如格式或缓冲区数量设置不正确,或者没有设置OnImageAvailableListener的回调Handler,导致回调无法触发。需要检查ImageReader的初始化参数,并确保回调监听器被正确设置,并指定了合适的Handler线程。总结可能的问题点: 1. ImageReader的Surface未被添加到CaptureSession的surfaceList中。 2.在创建CaptureRequest时未将ImageReader的Surface作为target添加。 3. ImageReader初始化参数不正确,如格式或maxImages。 4.未正确设置OnImageAvailableListener的回调Handler,导致线程阻塞。5.资源释放问题,可能在创建会话前关闭了ImageReader或其Surface。针对这些点,我需要逐一给出解决方案,并确保代码示例正确涵盖这些情况。同时,需要处理IllegalArgumentException错误,确保所有在CaptureRequest中使用的Surface都被正确配置到CaptureSession中。</think>### Camera2 API 中解决预览正常但 `ImageReader.OnImageAvailableListener` 未触发及 `IllegalArgumentException` 错误 --- #### **问题 1:`OnImageAvailableListener` 未触发** **原因分析** 1. **`ImageReader` 未绑定到 `CaptureSession`** 在创建 `CaptureSession` 时,必须将 `ImageReader` 的 `Surface` 包含在 `surfaceList` 中。否则,即使添加了 `ImageReader` 到捕获请求中,也会因未配置的 `Surface` 导致回调无法触发[^1][^3]。 2. **`CaptureRequest` 未添加 `ImageReader` 的 `Surface`** 如果 `CaptureRequest` 的 `Builder` 未通过 `addTarget()` 添加 `ImageReader` 的 `Surface`,图像数据将不会流向 `ImageReader`[^3]。 3. **`ImageReader` 初始化参数错误** `ImageFormat` 或 `maxImages` 参数不匹配会导致资源分配失败。例如,某些设备不支持 `YUV_420_888` 格式,或 `maxImages` 过小导致缓冲区不足[^3]。 --- #### **问题 2:`IllegalArgumentException: CaptureRequest contains unconfigured Input/Output Surface`** **原因分析** - **未在 `CaptureSession` 中配置的 `Surface` 被用于 `CaptureRequest`** `CaptureSession` 的 `surfaceList` 必须包含所有后续 `CaptureRequest` 中使用的 `Surface`。若漏掉 `ImageReader` 的 `Surface`,则会导致此错误[^3][^4]。 --- #### **完整解决方案** ##### **步骤 1:正确初始化 `ImageReader`** ```java // 使用支持的格式(如 YUV_420_888)和足够的缓冲区数量 mImageReader = ImageReader.newInstance( mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 2 // 至少 2 个缓冲区 ); // 设置回调并指定 Handler 线程 HandlerThread imageHandlerThread = new HandlerThread("ImageCallback"); imageHandlerThread.start(); mImageReader.setOnImageAvailableListener( mImageAvailableListener, new Handler(imageHandlerThread.getLooper()) ); ``` ##### **步骤 2:将 `ImageReader` 的 `Surface` 添加到 `CaptureSession`** ```java List<Surface> surfaceList = new ArrayList<>(); // 添加预览 Surface if (mSurfaceTexture != null) { mSurfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); Surface previewSurface = new Surface(mSurfaceTexture); surfaceList.add(previewSurface); } // 添加 ImageReader 的 Surface if (mImageReader != null) { surfaceList.add(mImageReader.getSurface()); } // 确保 surfaceList 非空 if (surfaceList.isEmpty()) { throw new IllegalStateException("No valid output surfaces"); } ``` ##### **步骤 3:在 `CaptureRequest` 中添加所有目标** ```java mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); // 添加所有 Surface 到 CaptureRequest for (Surface surface : surfaceList) { mPreviewRequestBuilder.addTarget(surface); } ``` ##### **步骤 4:创建 `CaptureSession`** ```java mCameraDevice.createCaptureSession(surfaceList, new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { mCaptureSession = session; try { // 设置重复请求 mCaptureSession.setRepeatingRequest( mPreviewRequestBuilder.build(), mCaptureCallback, mCameraHandler ); } catch (CameraAccessException e) { Log.e(TAG, "Failed to start preview: " + e); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { Log.e(TAG, "CaptureSession configuration failed"); } }, mCameraHandler); ``` --- #### **关键代码修改对比** | 原代码问题 | 修改后代码 | |---------|----------| | `surfaceList` 仅包含预览 Surface | `surfaceList` 同时包含预览和 `ImageReader` 的 Surface | | `CaptureRequest` 未添加 `ImageReader` 的 Surface | 循环添加所有 `Surface` 到 `CaptureRequest` | | 未指定 `ImageReader` 的回调线程 | 显式设置 `Handler` 避免线程阻塞 | --- #### **公式推导示例** 假设设备支持的最大帧率为 $f_{\text{max}}$,`ImageReader` 的缓冲区数量 $n$ 应满足: $$ n \geq \left\lceil \frac{t_{\text{processing}}}{t_{\text{frame}}} \right\rceil $$ 其中 $t_{\text{processing}}$ 是单帧处理时间,$t_{\text{frame}} = \frac{1}{f_{\text{max}}}$。 --- #### **相关问题** 1. 如何检测设备支持的 `ImageFormat` 和 `maxImages`? 2. 在低端设备上如何优化 `ImageReader` 的性能? 3. 如何处理 `Surface` 生命周期以避免内存泄漏? 4. 如何调试 `CaptureSession` 的配置失败问题? 5. 在多 Surface 场景下如何平衡预览流畅度和图像处理效率?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值