相关的文件如下:
service camera-provider-2-4 /vendor/bin/hw/android.hardware.camera.provider@2.4-service
class hal
user cameraserver
group audio camera input drmrpc
ioprio rt 4
capabilities SYS_NICE
writepid /dev/cpuset/camera-daemon/tasks /dev/stune/foreground/tasks
CameraProvider 守护进程由 init 进程启动。
int main()
{
ALOGI("Camera provider Service is starting.");
// The camera HAL may communicate to other vendor components via
// /dev/vndbinder
android::ProcessState::initWithDriver("/dev/vndbinder");
/* 核心工作都在这个函数里面,下面分析 */
return defaultPassthroughServiceImplementation<ICameraProvider>("legacy/0", /*maxThreads*/ 6);
}
/* 模板函数,Interface = ICameraProvider */
template<class Interface>
__attribute__((warn_unused_result))
status_t defaultPassthroughServiceImplementation(std::string name, size_t maxThreads = 1) {
/* 在上一篇分析过了,第一次执行这个函数会open(/dev/hwbinder) */
configureRpcThreadpool(maxThreads, true);
/*
* 核心在这个函数
* 这个函数做了两件事:
* 1、得到了 CameraProvider 实例化对象
* 2、注册 CameraProvider 实例化对象
* 后面分析
*/
status_t result = registerPassthroughServiceImplementation(name);
/*
* 上一篇同样分析过这个,进入线程等待并处理binder消息
* 当然这里的流程跟HwServiceManager稍微有些不一样
* 后面 2.5 分析
*/
joinRpcThreadpool();
return 0;
}
/* 模板函数,Interface = ICameraProvider */
template<class Interface>
__attribute__((warn_unused_result))
status_t registerPassthroughServiceImplementation(std::string name = "default") {
/*
* 就是调用 ICameraProvider::getService()
* getStub = ture 时,getservice 以 passthrough 模式打开 HAL 实现
* 所以这个会得到 CameraProvider 实例化对象(不是binder代理)
* 后面 2.3 分析
*/
sp service = Interface::getService(name, true /* getStub */);
/*
* 将 CameraProvider 注册为一个服务
* 其他进程需要使用 camera 的 hal 层时通过 binder 得到 CameraProvider 代理类即可操作camera hal 层
* 不需要像以前一样每次都 dlopen(xxx.so)
* 后面 2.4 分析
*/
status_t status = service->registerAsService(name);
return status;
}
// CameraProviderAll.cpp
::android::sp ICameraProvider::getService(const std::string &serviceName, const bool getStub) {
using ::android::hardware::defaultServiceManager;
using ::android::hardware::details::waitForHwService;
using ::android::hardware::getPassthroughServiceManager;
using ::android::hardware::Return;
using ::android::sp;
using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
sp iface = nullptr;
const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager();
Return transportRet = sm->getTransport(ICameraProvider::descriptor, serviceName);
Transport transport = transportRet;
const bool vintfHwbinder = (transport == Transport::HWBINDER);
const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
#ifdef __ANDROID_TREBLE__
#ifdef __ANDROID_DEBUGGABLE__
const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
const bool trebleTestingOverride = env && !strcmp(env, "true");
const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
#else // __ANDROID_TREBLE__ but not __ANDROID_DEBUGGABLE__
const bool trebleTestingOverride = false;
const bool vintfLegacy = false;
#endif // __ANDROID_DEBUGGABLE__
#else // not __ANDROID_TREBLE__
const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
const bool trebleTestingOverride = env && !strcmp(env, "true");
const bool vintfLegacy = (transport == Transport::EMPTY);
#endif // __ANDROID_TREBLE__
for (int tries = 0; !getStub && (vintfHwbinder || (vintfLegacy && tries == 0)); tries++) {
/*
* getStub = flase 才走这个分支
* getService 会先获取 binder 服务,如果失败了才会获取 passthrough 服务
*/
if (vintfHwbinder && tries > 0) {
/* 等待 HwServiceManager 成功启动*/
waitForHwService(ICameraProvider::descriptor, serviceName);
}
/* 获取 CameraProvider 代理类对象(binder) */
Return> ret =
sm->get(ICameraProvider::descriptor, serviceName);
sp<::android::hidl::base::V1_0::IBase> base = ret;
if (base == nullptr) {
if (tries > 0) {
ALOGW("ICameraProvider: found null hwbinder interface");
}continue;
}
/* 转换为 BpHwCameraProvider 对象 */
Return> castRet = ICameraProvider::castFrom(base, true /* emitError */);
if (!castRet.isOk()) {
if (castRet.isDeadObject()) {
ALOGW("ICameraProvider: found dead hwbinder service");
continue;
} else {
ALOGW("ICameraProvider: cannot call into hwbinder service: %s; No permission? Check for selinux denials.", castRet.description().c_str());
break;
}
}
iface = castRet;
if (iface == nullptr) {
ALOGW("ICameraProvider: received incompatible service; bug in hwservicemanager?");
break;
}
/* 所以这里返回的是 BpHwCameraProvider 对象 */
return iface;
}
if (getStub || vintfPassthru || vintfLegacy) {
/*
* getStub = true 时或者 binder 获取失败时走这个分支
* getservice 以 passthrough 模式打开 HAL 实现
*/
/*
* 获得 Passthrough 模式的服务管理器
* 其实就是 new PassthroughServiceManager 得到实例化对象
*/
const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
if (pm != nullptr) {
/*
* 这里会根据传入的 descriptor 字符串,找到 CameraProvider.cpp 生成的 so 文件
* 就是 [email protected]
* 然后使用这个库中的 HIDL_FETCH_ICameraProvider() 函数得到 CameraProvider 实例化对象
* 后面会分析这个函数
*/
Return> ret =
pm->get(ICameraProvider::descriptor, serviceName);
if (ret.isOk()) {
sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
if (baseInterface != nullptr) {
iface = ICameraProvider::castFrom(baseInterface);
if (!getStub || trebleTestingOverride) {
iface = new BsCameraProvider(iface);
}
}
}
}
}
/* 所以这里返回的就是 CameraProvider 实例化对象 */
return iface;
}
/*
* ServiceManagement.cpp
* pm->get(ICameraProvider::descriptor, serviceName);
* ICameraProvider::descriptor = "[email protected]::ICameraProvider"
*/
Return> get(const hidl_string& fqName, const hidl_string& name) override {
sp ret = nullptr;
/*
* 打开库,openLibs 后面分析
* 这里使用了匿名回调函数
*/
openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
IBase* (*generator)(const char* name);
/* 分析完 openLibs() 知道这里就是得到 HIDL_FETCH_ICameraProvider() 函数*/
*(void **)(&generator) = dlsym(handle, sym.c_str());
/* 调用 HIDL_FETCH_ICameraProvider() 函数得到 CameraProvider 实例化对象
* 后面分析 HIDL_FETCH_ICameraProvider() 函数
*/
ret = (*generator)(name.c_str());
registerReference(fqName, name);
/*
* 吐槽一下这个:false 竟然表明成功...
*/
return false;
});
/* 所以返回的是 CameraProvider 实例化对象 */
return ret;
}
static void openLibs(const std::string& fqName,
std::function<bool /* continue */(void* /* handle */,
const std::string& /* lib */, const std::string& /* sym */)> eachLib) {
//fqName looks like [email protected]::IFoo
/* fqName = "[email protected]::ICameraProvider" */
size_t idx = fqName.find("::");
/* 得到 "[email protected]" 字符串 */
std::string packageAndVersion = fqName.substr(0, idx);
/* 得到 "ICameraProvider" 字符串 */
std::string ifaceName = fqName.substr(idx + strlen("::"));
/* 得到 "[email protected]" 字符串 */
const std::string prefix = packageAndVersion + "-impl";
/* 得到 "HIDL_FETCH_ICameraProvider" 字符串 */
const std::string sym = "HIDL_FETCH_" + ifaceName;
const int dlMode = RTLD_LAZY;
void *handle = nullptr;
dlerror(); // clear
/* 在这四个目录下搜索 "[email protected]" */
std::vector<std::string> paths = {HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
HAL_LIBRARY_PATH_VNDK_SP, HAL_LIBRARY_PATH_SYSTEM};
for (const std::string& path : paths) {
std::vector<std::string> libs = search(path, prefix, ".so");
for (const std::string &lib : libs) {
const std::string fullPath = path + lib;
/* 打开库 */
if (path != HAL_LIBRARY_PATH_SYSTEM) {
handle = android_load_sphal_library(fullPath.c_str(), dlMode);
} else {
handle = dlopen(fullPath.c_str(), dlMode);
}
/* 调用回调函数。 这个回调是匿名的, 在上面 openLibs() 有说到 */
if (!eachLib(handle, lib, sym)) {
return;
}
}
}
}
/* CameraProvider.cpp */
ICameraProvider* HIDL_FETCH_ICameraProvider(const char* name) {
if (strcmp(name, kLegacyProviderName) != 0) {
return nullptr;
}
/*
* 很简单,就是 new CameraProvider 实例
* 但是要注意,在构造函数中打开了 HAL 层
* CameraProvider 与 Camera HAL 联系了起来
* 后面分析
*/
CameraProvider* provider = new CameraProvider();
/* 返回 CameraProvider 实例化对象 */
return provider;
}
CameraProvider::CameraProvider() :
/*
* 调用父类的构造函数
* 这个回调会在后面使用到,请留意
*/
camera_module_callbacks_t({sCameraDeviceStatusChange,
sTorchModeStatusChange}) {
/* 继续分析 */
mInitFailed = initialize();
}
bool CameraProvider::initialize() {
camera_module_t *rawModule;
/*
* 就是这里了,打开 HAL
* 这里就不分析了
*/
int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
(const hw_module_t **)&rawModule);
/*
* 将得到的 hw_module_t 结构体再封装都、多一层
* 之后会使用这个对象调用 HAL 层接口
*/
mModule = new CameraModule(rawModule);
/* 得到一些 Camera 的基本信息 */
err = mModule->init();
// Setup callback now because we are going to try openLegacy next
/*
* 设置回调,在 CameraProvider() 构造函数中构造的回调
* class CameraProvider 继承于 class camera_module_callbacks_t 所以可以这样调用
* 看意思应该就是 camera 状态改变的时候 HAL 层会调用这个回调通知 CameraProvider
*/
err = mModule->setCallbacks(this);
mPreferredHal3MinorVersion = property_get_int32("ro.camera.wrapper.hal3TrebleMinorVersion", 3);
switch(mPreferredHal3MinorVersion) {
case 2:
case 3:
// OK
break;
default:
mPreferredHal3MinorVersion = 3;
}
/* 得到 camera 的个数 */
mNumberOfLegacyCameras = mModule->getNumberOfCameras();
for (int i = 0; i < mNumberOfLegacyCameras; i++) {
struct camera_info info;
/* 获得每一个 camera 的信息 */
auto rc = mModule->getCameraInfo(i, &info);
if (checkCameraVersion(i, info) != OK) {
ALOGE("%s: Camera version check failed!", __func__);
mModule.clear();
return true;
}
char cameraId[kMaxCameraIdLen];
snprintf(cameraId, sizeof(cameraId), "%d", i);
std::string cameraIdStr(cameraId);
mCameraStatusMap[cameraIdStr] = CAMERA_DEVICE_STATUS_PRESENT;
mCameraIds.add(cameraIdStr);
// initialize mCameraDeviceNames and mOpenLegacySupported
mOpenLegacySupported[cameraIdStr] = false;
int deviceVersion = mModule->getDeviceVersion(i);
mCameraDeviceNames.add(
std::make_pair(cameraIdStr,
getHidlDeviceName(cameraIdStr, deviceVersion)));
if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
mModule->isOpenLegacyDefined()) {
// try open_legacy to see if it actually works
struct hw_device_t* halDev = nullptr;
int ret = mModule->openLegacy(cameraId, CAMERA_DEVICE_API_VERSION_1_0, &halDev);
if (ret == 0) {
mOpenLegacySupported[cameraIdStr] = true;
halDev->close(halDev);
mCameraDeviceNames.add(
std::make_pair(cameraIdStr,
getHidlDeviceName(cameraIdStr, CAMERA_DEVICE_API_VERSION_1_0)));
} else if (ret == -EBUSY || ret == -EUSERS) {
// Looks like this provider instance is not initialized during
// system startup and there are other camera users already.
// Not a good sign but not fatal.
ALOGW("%s: open_legacy try failed!", __FUNCTION__);
}
}
}
return false; // mInitFailed
}
至此,我们就完全明白了 CameraProvider::getService(name, true) 是如何一步步得到 CameraProvider 实例化对象的。
接下来分析如何将 CameraProvider 实例化对象注册为一个服务。
/* CameraProviderAll.cpp */
::android::status_t ICameraProvider::registerAsService(const std::string &serviceName) {
::android::hardware::details::onRegistration("[email protected]", "ICameraProvider", serviceName);
/*
* 得到 BpHwServiceManager 对象
* 就是 HwServiceManager 对象的 binder 代理
* 后面会分析如何得到 BpHwServiceManager 对象
*/
const ::android::sp<::android::hidl::manager::V1_0::IServiceManager> sm
= ::android::hardware::defaultServiceManager();
/*
* 调用 BpHwServiceManager::add() 注册服务
* 后面分析
*/
::android::hardware::Return<bool> ret = sm->add(serviceName.c_str(), this);
return ret.isOk() && ret ? ::android::OK : ::android::UNKNOWN_ERROR;
}
/* 分析如何得到 BpHwServiceManager 对象 */
/* ServiceManagement.cpp */
sp<IServiceManager1_0> defaultServiceManager() {
return defaultServiceManager1_1();
}
/* 分析如何得到 BpHwServiceManager 对象 */
/* ServiceManagement.cpp */
sp<IServiceManager1_1> defaultServiceManager1_1() {
{
AutoMutex _l(details::gDefaultServiceManagerLock);
/* 如果不是第一次调用这个函数的话直接返回之前得到的 gDefaultServiceManager */
if (details::gDefaultServiceManager != NULL) {
return details::gDefaultServiceManager;
}
/*
* 等待 HwServiceManager 服务启动完毕, 上一篇介绍过这个
* 是通过 "hwservicemanager.ready" 属性的值判断的
*/
waitForHwServiceManager();
while (details::gDefaultServiceManager == NULL) {
/*
* 得到 BpHwServiceManager
* 需要注意 ProcessState::self()->getContextObject(NULL) 它就是得到 Handle = 0 的 HwBinder 对象
* 由这个 HwBinder 对象构造出了 BpHwServiceManager 对象
*/
details::gDefaultServiceManager =
fromBinder<IServiceManager1_1, BpHwServiceManager, BnHwServiceManager>(
ProcessState::self()->getContextObject(NULL));
}
}
/* 返回 BpHwServiceManager 对象 */
return details::gDefaultServiceManager;
}
/* 分析如何注册 CameraProvider 对象 */
/* ServiceManagerAll.cpp */
::android::hardware::Return<bool> BpHwServiceManager::add(const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service){
/* 接着分析 */
::android::hardware::Return<bool> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_add(this, this, name, service);
return _hidl_out;
}
/* 分析如何注册 CameraProvider 对象 */
/* ServiceManagerAll.cpp */
::android::hardware::Return<bool> BpHwServiceManager::_hidl_add(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service) {
/* 这个是用来发送数据的 */
::android::hardware::Parcel _hidl_data;
/* 这个是用来接收返回数据的 */
::android::hardware::Parcel _hidl_reply;
::android::status_t _hidl_err;
::android::hardware::Status _hidl_status;
bool _hidl_out_success;
/* 构造要发送的数据,写入一个固定的字符串 */
_hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
if (_hidl_err != ::android::OK) { goto _hidl_error; }
size_t _hidl_name_parent;
/* 构造要发送的数据,写入要注册服务的名字 */
_hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
_hidl_err = ::android::hardware::writeEmbeddedToParcel(
name,
&_hidl_data,
_hidl_name_parent,
0 /* parentOffset */);
if (service == nullptr) {
_hidl_err = _hidl_data.writeStrongBinder(nullptr);
} else {
/* toBinder() 会根据传入的 CameraProvider 对象构造出一个 BnHwCameraProvider 对象
* 之后会开启线程等待其他进程使用 CameraProvider 服务,而具体如何处理这些服务请求就是由 BnHwCameraProvider 对象来执行的
* 当然,最终还是会调用到 CameraProvider 对象上
* BnHwCameraProvider 对象就是一个中转站
*/
::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<
::android::hidl::base::V1_0::IBase>(service);
if (_hidl_binder.get() != nullptr) {
/*
* 把得到的 BnHwCameraProvider 对象的地址写入 _hidl_data
* 之后接收到其他进程的请求时,会从内核中得到这个地址,根据这个地址得到 BnHwCameraProvider,然后做一些处理
*/
_hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);
} else {
_hidl_err = ::android::UNKNOWN_ERROR;
}
}
if (_hidl_err != ::android::OK) { goto _hidl_error; }
/*
* 开启新的线程, 这个线程就是 CameraProvider 服务了
* 就想上面说的那样,在这个线程里面会等待其他进程使用 CameraProvider 服务
* 当接收到请求之后,从内核中得到 BnHwCameraProvider 的地址,通过 BnHwCameraProvider 处理请求
*/
::android::hardware::ProcessState::self()->startThreadPool();
/*
* 发送数据, binder 进程间调用
* 最终就通过 binder 调用了 ServiceManager::add()
* 后面分析
*/
_hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(2 /* add */, _hidl_data, &_hidl_reply);
if (_hidl_err != ::android::OK) { goto _hidl_error; }
_hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
_hidl_err = _hidl_reply.readBool(&_hidl_out_success);
atrace_end(ATRACE_TAG_HAL);
_hidl_status.setFromStatusT(_hidl_err);
return ::android::hardware::Return<bool>(_hidl_out_success);
_hidl_error:
_hidl_status.setFromStatusT(_hidl_err);
return ::android::hardware::Return<bool>(_hidl_status);
}
/* ServiceManager.cpp */
Return<bool> ServiceManager::add(const hidl_string& name, const sp<IBase>& service) {
bool isValidService = false;
/* 调用进程的PID */
pid_t pid = IPCThreadState::self()->getCallingPid();
auto context = mAcl.getContext(pid);
auto ret = service->interfaceChain([&](const auto &interfaceChain) {
for(size_t i = 0; i < interfaceChain.size(); i++) {
std::string fqName = interfaceChain[i];
if (!mAcl.canAdd(fqName, context, pid)) {
return;
}
}
for(size_t i = 0; i < interfaceChain.size(); i++) {
std::string fqName = interfaceChain[i];
PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
HidlService *hidlService = ifaceMap.lookup(name);
if (hidlService == nullptr) {
/* 注册 HwServiceManager 走这个分支 */
ifaceMap.insertService(
std::make_unique(fqName, name, service, pid));
} else {
if (hidlService->getService() != nullptr) {
auto ret = hidlService->getService()->unlinkToDeath(this);
ret.isOk(); // ignore
}
/*
* 注册 CameraProvider 等服务走这个分支
* 其实就是插入一个map里面,当需要的时候从map中取出
* service 里面保留的是 CameraProvider 服务的一些信息:Handle 之类的
*/
hidlService->setService(service, pid);
}
ifaceMap.sendPackageRegistrationNotification(fqName, name);
}
/*
* 连接死亡通知
* 当 CameraProvider 服务挂掉的时候会通知 HwServiceManager 做清理工作
*/
auto linkRet = service->linkToDeath(this, 0 /*cookie*/);
linkRet.isOk();
isValidService = true;
});
if (!ret.isOk()) {
LOG(ERROR) << "Failed to retrieve interface chain.";
return false;
}
return isValidService;
}
至此,我们完全明白注册 CameraProvider 服务的流程了。
接下来分析 CameraProvider 服务如何处理请求
由 2.2 我们知道,得到 CameraProvider 实例化对象之后马上就注册了 CameraProvider 实例化对象,然后调用 joinRpcThreadpool() 函数进入循环等待请求。当然,其实在注册 CameraProvider 实例化对象的时候调用了 startThreadPool() 函数就已经有线程在等待了,startThreadPool()会调用 joinRpcThreadpool() 函数。而这里的 joinRpcThreadpool() 其实就是把主线程也放入线程池中等待请求,防止这个进程退出。
/* HidlTransportSupport.cpp */
void joinRpcThreadpool() {
joinBinderRpcThreadpool();
}
/* HidlTransportSupport.cpp */
void joinBinderRpcThreadpool() {
IPCThreadState::self()->joinThreadPool();
}
/* IPCThreadState.cpp */
void IPCThreadState::joinThreadPool(bool isMain)
{
mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
status_t result;
do {
/* 循环处理请求 */
processPendingDerefs();
/*
* 得到请求命令,并处理它
* 后面分析
*/
result = getAndExecuteCommand();
} while (result != -ECONNREFUSED && result != -EBADF);
/*
* 如果走到这表明出现了一些错误
* 需要告诉驱动这个线程不再处理消息了,既退出 LOOPER
*/
mOut.writeInt32(BC_EXIT_LOOPER);
talkWithDriver(false);
}
status_t IPCThreadState::getAndExecuteCommand()
{
status_t result;
int32_t cmd;
/*
* 这个函数会调用 ioctl() 读取请求,并放入 mIn 中
* 后面分析
*/
result = talkWithDriver();
if (result >= NO_ERROR) {
size_t IN = mIn.dataAvail();
/* 取出 cmd */
cmd = mIn.readInt32();
/*
* 处理 cmd
* 后面分析
*/
result = executeCommand(cmd);
return result;
}
/* 默认 doReceive = true 表示是读 binder */
status_t IPCThreadState::talkWithDriver(bool doReceive)
{
binder_write_read bwr;
// Is the read buffer empty?
const bool needRead = mIn.dataPosition() >= mIn.dataSize();
// We don't want to write anything if we are still reading
// from data left in the input buffer and the caller
// has requested to read the next data.
const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
bwr.write_size = outAvail;
bwr.write_buffer = (uintptr_t)mOut.data();
// This is what we'll read.
if (doReceive && needRead) {
bwr.read_size = mIn.dataCapacity();
/* 将读到的数据放到这个 buf 中 */
bwr.read_buffer = (uintptr_t)mIn.data();
} else {
bwr.read_size = 0;
bwr.read_buffer = 0;
}
bwr.write_consumed = 0;
bwr.read_consumed = 0;
status_t err;
do {
/*
* 调用 ioctl() 获得请求
* 数据保存在 bwr
*/
if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
err = NO_ERROR;
else
err = -errno;
} while (err == -EINTR);
if (err >= NO_ERROR) {
if (bwr.write_consumed > 0) {
if (bwr.write_consumed < mOut.dataSize())
mOut.remove(0, bwr.write_consumed);
else
mOut.setDataSize(0);
}
/* 我们走的是 read 分支 */
if (bwr.read_consumed > 0) {
/* 得到数据的大小 */
mIn.setDataSize(bwr.read_consumed);
mIn.setDataPosition(0);
}
return NO_ERROR;
}
return err;
}
status_t IPCThreadState::executeCommand(int32_t cmd)
{
BHwBinder* obj;
RefBase::weakref_type* refs;
status_t result = NO_ERROR;
switch ((uint32_t)cmd) {
......
/*
* 我们只关注这个 cmd
* 其它 cmd 都与我们无关的
*/
case BR_TRANSACTION:
{
binder_transaction_data tr;
/* 取出数据 */
result = mIn.read(&tr, sizeof(tr));
Parcel buffer;
buffer.ipcSetDataReference(
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
const pid_t origPid = mCallingPid;
const uid_t origUid = mCallingUid;
const int32_t origStrictModePolicy = mStrictModePolicy;
const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
mCallingPid = tr.sender_pid;
mCallingUid = tr.sender_euid;
mLastTransactionBinderFlags = tr.flags;
Parcel reply;
status_t error;
bool reply_sent = false;
/* 构造一个匿名回调函数,返回值使用这个回调函数发送 */
auto reply_callback = [&] (auto &replyParcel) {
reply_sent = true;
if ((tr.flags & TF_ONE_WAY) == 0) {
replyParcel.setError(NO_ERROR);
/* 通过 binder 将调用结果返回 */
sendReply(replyParcel, 0);
} else {
ALOGE("Not sending reply in one-way transaction");
}
};
if (tr.target.ptr) {
/* tr.cookie 里面保存的就是之前说的 BnHwCameraProvider 的地址 */
if (reinterpret_cast(
tr.target.ptr)->attemptIncStrong(this)) {
/* 调用 BnHwCameraProvider::transact() 函数 */
error = reinterpret_cast(tr.cookie)->transact(tr.code, buffer,
&reply, tr.flags, reply_callback);
reinterpret_cast(tr.cookie)->decStrong(this);
} else {
error = UNKNOWN_TRANSACTION;
}
} else {
/* 上一篇分析过这个, 这里是 HwServiceManager 走的分支 */
error = mContextObject->transact(tr.code, buffer, &reply, tr.flags, reply_callback);
}
}
break;
......
default:
result = UNKNOWN_ERROR;
break;
}
if (result != NO_ERROR) {
mLastError = result;
}
return result;
}
/*
* BnHwCameraProvider::transact()
* BnHwCameraProvider 没有实现这个函数
* 所以调用父类的 transact()
* Binder.cpp
*/
status_t BHwBinder::transact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags, TransactCallback callback)
{
data.setDataPosition(0);
status_t err = NO_ERROR;
switch (code) {
default:
/* 直接调用 onTransact(), BnHwCameraProvider 实现了这个函数 */
err = onTransact(code, data, reply, flags,
[&](auto &replyParcel) {
replyParcel.setDataPosition(0);
if (callback != NULL) {
/* 通过回调函数,返回进程间调用的结果 */
callback(replyParcel);
}
});
break;
}
return err;
}
/* 这里就不详细分析了, 总之最后掉调用到 CameraProvider 提供的接口 */
::android::status_t BnHwCameraProvider::onTransact(
uint32_t _hidl_code,
const ::android::hardware::Parcel &_hidl_data,
::android::hardware::Parcel *_hidl_reply,
uint32_t _hidl_flags,
TransactCallback _hidl_cb) {
::android::status_t _hidl_err = ::android::OK;
switch (_hidl_code) {
case 1 /* setCallback */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hardware::camera::provider::V2_4::BnHwCameraProvider::_hidl_setCallback(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 2 /* getVendorTags */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hardware::camera::provider::V2_4::BnHwCameraProvider::_hidl_getVendorTags(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 3 /* getCameraIdList */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hardware::camera::provider::V2_4::BnHwCameraProvider::_hidl_getCameraIdList(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 4 /* isSetTorchModeSupported */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hardware::camera::provider::V2_4::BnHwCameraProvider::_hidl_isSetTorchModeSupported(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 5 /* getCameraDeviceInterface_V1_x */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hardware::camera::provider::V2_4::BnHwCameraProvider::_hidl_getCameraDeviceInterface_V1_x(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 6 /* getCameraDeviceInterface_V3_x */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hardware::camera::provider::V2_4::BnHwCameraProvider::_hidl_getCameraDeviceInterface_V3_x(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 256067662 /* interfaceChain */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_interfaceChain(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 256131655 /* debug */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_debug(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 256136003 /* interfaceDescriptor */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_interfaceDescriptor(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 256398152 /* getHashChain */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_getHashChain(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 256462420 /* setHALInstrumentation */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != true) {
return ::android::UNKNOWN_ERROR;
}
configureInstrumentation();
break;
}
case 256660548 /* linkToDeath */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
break;
}
case 256921159 /* ping */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_ping(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 257049926 /* getDebugInfo */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_getDebugInfo(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 257120595 /* notifySyspropsChanged */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != true) {
return ::android::UNKNOWN_ERROR;
}
_hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_notifySyspropsChanged(this, _hidl_data, _hidl_reply, _hidl_cb);
break;
}
case 257250372 /* unlinkToDeath */:
{
bool _hidl_is_oneway = _hidl_flags & ::android::hardware::IBinder::FLAG_ONEWAY;
if (_hidl_is_oneway != false) {
return ::android::UNKNOWN_ERROR;
}
break;
}
default:
{
return ::android::hidl::base::V1_0::BnHwBase::onTransact(
_hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
}
}
if (_hidl_err == ::android::UNEXPECTED_NULL) {
_hidl_err = ::android::hardware::writeToParcel(
::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),
_hidl_reply);
}return _hidl_err;
}
至此,CameraProvider 服务如何得到请求和处理请求的过程也非常清楚了
接下来看一下是哪个进程会使用到 CameraProvider 服务
service cameraserver /system/bin/cameraserver
class main
user cameraserver
group audio camera input drmrpc
ioprio rt 4
writepid /dev/cpuset/camera-daemon/tasks /dev/stune/top-app/tasks
int main(int argc __unused, char** argv __unused)
{
signal(SIGPIPE, SIG_IGN);
// Set 3 threads for HIDL calls
/*
* 见了很多次了,但是这里open(/dev/binder)不是open(/dev/hwbinder)
* 虽然这两个节点用的是同一套驱动代码,但是使用途径不一样
* 当然原理是一模一样的
*/
hardware::configureRpcThreadpool(3, /*willjoin*/ false);
sp<ProcessState> proc(ProcessState::self());
/*
* 获得 ServiceManager 的代理类 BpServiceManager, 注意不是 HwServiceManager 的代理类
* ServiceManager 这个服务管理器是用来跟上层交互的
* 原理跟 HwServiceManager 一样就不分析了
*/
sp<IServiceManager> sm = defaultServiceManager();
ALOGI("ServiceManager: %p", sm.get());
/*
* 做了两件事
* 1、得到 CameraService 实例化对象
* 2、注册 CameraService 实例化对象
* 后面分析
*/
CameraService::instantiate();
/* 见过很多次了, 就不分析了 */
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
/*
* BinderService 是 CameraService 的父类
* 模板类 SERVICE = CameraService
*/
template<typename SERVICE>
class BinderService
{
public:
/* 类属性的, 所以可以直接调用 */
static void instantiate() {
/* 接着分析 */
publish();
}
static status_t publish(bool allowIsolated = false) {
/* 得到 ServiceManager 的代理类 BpServiceManager */
sp<IServiceManager> sm(defaultServiceManager());
/*
* SERVICE = CameraService
* 注册 CameraService 实例化对象
*/
return sm->addService(
String16(SERVICE::getServiceName()),
/* new CameraService() 得到实例化对象,智能指针第一次引用回调用 onFirstRef() 函数, 后面分析 */
new SERVICE(), allowIsolated);
}
};
/* CameraService.cpp */
void CameraService::onFirstRef()
{
BnCameraService::onFirstRef();
BatteryNotifier& notifier(BatteryNotifier::getInstance());
notifier.noteResetCamera();
notifier.noteResetFlashlight();
status_t res = INVALID_OPERATION;
/* 核心在这, 接着分析 */
res = enumerateProviders();
if (res == OK) {
mInitialized = true;
}
CameraService::pingCameraServiceProxy();
}
status_t CameraService::enumerateProviders() {
status_t res;
Mutex::Autolock l(mServiceLock);
if (nullptr == mCameraProviderManager.get()) {
/* 第一次执行走这 */
mCameraProviderManager = new CameraProviderManager();
/* 接着分析 */
res = mCameraProviderManager->initialize(this);
}
mNumberOfCameras = mCameraProviderManager->getCameraCount();
mNumberOfNormalCameras =
mCameraProviderManager->getAPI1CompatibleCameraCount();
mCameraProviderManager->setUpVendorTags();
if (nullptr == mFlashlight.get()) {
mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
}
res = mFlashlight->findFlashUnits();
for (auto& cameraId : mCameraProviderManager->getCameraDeviceIds()) {
String8 id8 = String8(cameraId.c_str());
bool cameraFound = false;
{
Mutex::Autolock lock(mCameraStatesLock);
auto iter = mCameraStates.find(id8);
if (iter != mCameraStates.end()) {
cameraFound = true;
}
}
onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
if (mFlashlight->hasFlashUnit(id8)) {
mTorchStatusMap.add(id8, TorchModeStatus::AVAILABLE_OFF);
}
}
return OK;
}
/* CameraProviderManager.cpp */
status_t CameraProviderManager::initialize(wp<CameraProviderManager::StatusListener> listener,
/* proxy 是默认值, proxy = sHardwareServiceInteractionProxy */
ServiceInteractionProxy* proxy) {
std::lock_guard<std::mutex> lock(mInterfaceMutex);
/* listener = CameraService 对象 */
mListener = listener;
/* proxy = sHardwareServiceInteractionProxy */
mServiceProxy = proxy;
bool success = mServiceProxy->registerForNotifications(
/* instance name, empty means no filter */ "",
this);
/* 接着分析 */
addProviderLocked(kLegacyProviderName, /*expected*/ false);
return OK;
}
/* CameraProviderManager.cpp */
status_t CameraProviderManager::addProviderLocked(const std::string& newProvider, bool expected) {
sp<provider::V2_4::ICameraProvider> interface;
/*
* 上面分析过 mServiceProxy = sHardwareServiceInteractionProxy
* 这里 getService(newProvider) 其实就是得到 CameraProvider 的代理类
* 所以 CameraService 与 CameraProvider 联系起来了
* 接着分析这个函数 HardwareServiceInteractionProxy::getService()
*/
interface = mServiceProxy->getService(newProvider);
sp<ProviderInfo> providerInfo =
new ProviderInfo(newProvider, interface, this);
status_t res = providerInfo->initialize();
if (res != OK) {
return res;
}
mProviders.push_back(providerInfo);
return OK;
}
virtual sp<hardware::camera::provider::V2_4::ICameraProvider> getService(
const std::string &serviceName) override {
/*
* 调用了 ICameraProvider::getService()
* 且 getStub 为默认值 getStub = flase
* 之前分析过,getStub = flase 会得到 CameraProvider 的代理类(binder)
*/
return hardware::camera::provider::V2_4::ICameraProvider::getService(serviceName);
}
至此,我们发现 CameraService 会使用 CameraProvider 服务。
同上上述分析,显然上层 framework 通过 ServiceManager( /dev/binder ) 得到 CameraService 服务,而 CameraService 通过 HwServiceManager( /dev/hwbinder ) 得到 CameraProvider 服务,而 CameraProvider 与 Camera HAL 绑定。这样上层 framework 就能够访问 Camera HAL 层了