Android 多进程同时打开相机
生活随笔
收集整理的這篇文章主要介紹了
Android 多进程同时打开相机
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載:多進程打開相機
多進程打開相機
只要滿足一定的條件是可以多進程打開相機
1、CameraService打開相機的入口
Status CameraService::connectDevice(const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,const String16& cameraId,const String16& clientPackageName,int clientUid,/*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {ATRACE_CALL();Status ret = Status::ok();String8 id = String8(cameraId);sp<CameraDeviceClient> client = nullptr;ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,/*api1CameraId*/-1,CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,clientUid, USE_CALLING_PID, API_2,/*legacyMode*/ false, /*shimUpdateOnly*/ false,/*out*/client);if(!ret.isOk()) {logRejected(id, getCallingPid(), String8(clientPackageName),ret.toString8());return ret;}*device = client;return ret; }2、進入connectHelper
template<class CALLBACK, class CLIENT> Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,int clientPid, apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,/*out*/sp<CLIENT>& device) {binder::Status ret = binder::Status::ok();String8 clientName8(clientPackageName);int originalClientPid = 0;ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and ""Camera API version %d", clientPid, clientName8.string(), cameraId.string(),(halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),static_cast<int>(effectiveApiLevel));sp<CLIENT> client = nullptr;{// Acquire mServiceLock and prevent other clients from connecting//1)加這個鎖的主要目的是防止不同應用同一時刻嘗試打開相機,比如一個應用正在打開相機,另外一個應用也在嘗試打開相機,這個時候就需要等待了std::unique_ptr<AutoConditionLock> lock =AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);if (lock == nullptr) {ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting).", clientPid);return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,"Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",cameraId.string(), clientName8.string(), clientPid);}// Enforce client permissions and do basic sanity checks//2)這個主要是對應用做一些基本的檢查//包括://1.檢測UID是否可信//2.檢測PID是否可信//3.檢測是否有anddroid.permission.CAMERA權限//4.檢測用戶是否在mAllowedusers中,即檢測是否是有效用戶,//mAllowedusers的賦值實在CameraserviceProxy.javaif(!(ret = validateConnectLocked(cameraId, clientName8,/*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {return ret;}// Check the shim parameters after acquiring lock, if they have already been updated and// we were doing a shim update, return immediatelyif (shimUpdateOnly) {auto cameraState = getCameraState(cameraId);if (cameraState != nullptr) {if (!cameraState->getShimParams().isEmpty()) return ret;}}status_t err;sp<BasicClient> clientTmp = nullptr;std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;//3)handleEvictionsLocked是處理多進程互斥邏輯的地方,//多進程同時打開相機的互斥邏輯就是在這個函數實現。//我們重點分析下這個函數if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,/*out*/&partial)) != NO_ERROR) {switch (err) {case -ENODEV:return STATUS_ERROR_FMT(ERROR_DISCONNECTED,"No camera device with ID \"%s\" currently available",cameraId.string());case -EBUSY:return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,"Higher-priority client using camera, ID \"%s\" currently unavailable",cameraId.string());default:return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,"Unexpected error %s (%d) opening camera \"%s\"",strerror(-err), err, cameraId.string());}}..............sp<BasicClient> tmp = nullptr;if(!(ret = makeClient(this, cameraCb, clientPackageName,cameraId, api1CameraId, facing,clientPid, clientUid, getpid(), legacyMode,halVersion, deviceVersion, effectiveApiLevel,/*out*/&tmp)).isOk()) {return ret;}client = static_cast<CLIENT*>(tmp.get());LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",__FUNCTION__);err = client->initialize(mCameraProviderManager, mMonitorTags);............if (shimUpdateOnly) {// If only updating legacy shim parameters, immediately disconnect clientmServiceLock.unlock();client->disconnect();mServiceLock.lock();} else {// Otherwise, add client to active clients listfinishConnectLocked(client, partial);}} // lock is destroyed, allow further connect calls// Important: release the mutex here so the client can call back into the service from its// destructor (can be at the end of the call)device = client;return ret; }3、分析handleEvictionsLocked
status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,/*out*/sp<BasicClient>* client,std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {ATRACE_CALL();status_t ret = NO_ERROR;std::vector<DescriptorPtr> evictedClients;DescriptorPtr clientDescriptor;{if (effectiveApiLevel == API_1) {// If we are using API1, any existing client for this camera ID with the same remote// should be returned rather than evicted to allow MediaRecorder to work properly.............}// Get current active client PIDs 獲取已經打開相機的所有pidstd::vector<int> ownerPids(mActiveClientManager.getAllOwners());//將當前正在打開相機的應用進程號也保存到ownerPids 中ownerPids.push_back(clientPid);//創建進程priorityScores,states ventorstd::vector<int> priorityScores(ownerPids.size());std::vector<int> states(ownerPids.size());// Get priority scores of all active PIDs //獲取所有ownerPids中的進程priority和statesstatus_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(), &ownerPids[0], /*out*/&states[0],/*out*/&priorityScores[0]);if (err != OK) {ALOGE("%s: Priority score query failed: %d",__FUNCTION__, err);return err;}// Update all active clients' priorities//將上一步獲取的進程優先級更新到mActiveClientManager中std::map<int,resource_policy::ClientPriority> pidToPriorityMap;for (size_t i = 0; i < ownerPids.size() - 1; i++) {pidToPriorityMap.emplace(ownerPids[i],resource_policy::ClientPriority(priorityScores[i], states[i]));}mActiveClientManager.updatePriorities(pidToPriorityMap);// Get state for the given cameraId// 獲取cameraId相機的狀態,Cameraservice啟動的時候會獲取所有相機的狀態auto state = getCameraState(cameraId);if (state == nullptr) {ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",clientPid, cameraId.string());// Should never get here because validateConnectLocked should have errored outreturn BAD_VALUE;}// Make descriptor for incoming client//由當前正在打開相機的cameraId,priorityScores,states,clientPid等信息//創建ClientDescriptor對象,key=cameraId;value=null;//ClientDescriptor未填充client,因為還未makeclientclientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),state->getConflicting(),//當前正在打開相機的priorityScorespriorityScores[priorityScores.size() - 1],clientPid,//當前正在打開相機的statesstates[states.size() - 1]);// Find clients that would be evicted// 在mActiveClientManager查找和上一步創建的ClientDescriptor存在沖突的所有client// 如果有沖突的client,都保存到evicted隊列中// evicted隊列中的所有client都需要關閉正在使用的相機,// 如果當前正在打開相機的client也在該evicted,說明當前client不能打開相機// 接下來會重點分析該函數實現auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);// If the incoming client was 'evicted,' higher priority clients have the camera in the// background, so we cannot do evictions//如果clientDescriptor(即當前應用)在evicted列表中,則說明當前相機應用的進程優先級較低,則本次打開相機失敗,上報的錯誤log如下if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"" priority).", clientPid);sp<BasicClient> clientSp = clientDescriptor->getValue();String8 curTime = getFormattedCurrentTime();//獲取與當前client存在沖突的clientauto incompatibleClients =mActiveClientManager.getIncompatibleClients(clientDescriptor);//打印當前client信息String8 msg = String8::format("%s : DENIED connect device %s client for package %s ""(PID %d, score %d state %d) due to eviction policy", curTime.string(),cameraId.string(), packageName.string(), clientPid,priorityScores[priorityScores.size() - 1],states[states.size() - 1]);//打印與當前client沖突的client信息for (auto& i : incompatibleClients) {msg.appendFormat("\n - Blocked by existing device %s client for package %s""(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",i->getKey().string(),String8{i->getValue()->getPackageName()}.string(),i->getOwnerId(), i->getPriority().getScore(),i->getPriority().getState());ALOGE(" Conflicts with: Device %s, client package %s (PID %"PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),i->getPriority().getScore(), i->getPriority().getState());}// Log the client's attemptMutex::Autolock l(mLogLock);mEventLog.add(msg);return -EBUSY;}//關閉evicted中client正在使用的相機 如果clientDescriptor不在evicted,則強制關閉evicted中其他正在使用相機的應用for (auto& i : evicted) {sp<BasicClient> clientSp = i->getValue();if (clientSp.get() == nullptr) {ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);// TODO: Remove thisLOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",__FUNCTION__);mActiveClientManager.remove(i);continue;}ALOGE("CameraService::connect evicting conflicting client for camera ID %s",i->getKey().string());//將有效evicted的client push到evictedClientsevictedClients.push_back(i);// Log the clients evictedlogEvent(String8::format("EVICT device %s client held by package %s (PID"" %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"" package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",i->getKey().string(), String8{clientSp->getPackageName()}.string(),i->getOwnerId(), i->getPriority().getScore(),i->getPriority().getState(), cameraId.string(),packageName.string(), clientPid,priorityScores[priorityScores.size() - 1],states[states.size() - 1]));// Notify the client of disconnection//通知evicted中client,相機馬上就要關閉了clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,CaptureResultExtras());}}// Do not hold mServiceLock while disconnecting clients, but retain the condition blocking// other clients from connecting in mServiceLockWrapper if heldmServiceLock.unlock();// Clear caller identity temporarily so client disconnect PID checks work correctlyint64_t token = IPCThreadState::self()->clearCallingIdentity();// Destroy evicted clients//關閉所有在evictedClients中的正在使用相機的應用 for (auto& i : evictedClients) {// Disconnect is blocking, and should only have returned when HAL has cleaned upi->getValue()->disconnect(); // Clients will remove themselves from the active client list}IPCThreadState::self()->restoreCallingIdentity(token);for (const auto& i : evictedClients) {ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",__FUNCTION__, i->getKey().string(), i->getOwnerId());ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);if (ret == TIMED_OUT) {ALOGE("%s: Timed out waiting for client for device %s to disconnect, ""current clients:\n%s", __FUNCTION__, i->getKey().string(),mActiveClientManager.toString().string());return -EBUSY;}if (ret != NO_ERROR) {ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), ""current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),ret, mActiveClientManager.toString().string());return ret;}}evictedClients.clear();// Once clients have been disconnected, relockmServiceLock.lock();// Check again if the device was unplugged or something while we weren't holding mServiceLockif ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {return ret;}*partial = clientDescriptor;return NO_ERROR; }4、分析mActiveClientManager.wouldEvict(clientDescriptor);
實現函數為wouldEvictLocked
ClientManager<KEY, VALUE, LISTENER>::wouldEvict(const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client) const {Mutex::Autolock lock(mLock);return wouldEvictLocked(client); } //returnIncompatibleClients為默認值false template<class KEY, class VALUE, class LISTENER> std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> ClientManager<KEY, VALUE, LISTENER>::wouldEvictLocked(const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client,bool returnIncompatibleClients) const {std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> evictList;// Disallow null clients, return inputif (client == nullptr) {evictList.push_back(client);return evictList;}//獲取當前進程的現關信息const KEY& key = client->getKey(); //key就是cameraidint32_t cost = client->getCost(); //cost 在getCameraState會介紹ClientPriority priority = client->getPriority(); //獲取優先級int32_t owner = client->getOwnerId(); //獲取進程pidint64_t totalCost = getCurrentCostLocked() + cost;// Determine the MRU of the owners tied for having the highest priority//獲取所有打開相機應用中優先級最高的pidint32_t highestPriorityOwner = owner;ClientPriority highestPriority = priority;for (const auto& i : mClients) {ClientPriority curPriority = i->getPriority();if (curPriority <= highestPriority) {// 值越小優先級越高highestPriority = curPriority;highestPriorityOwner = i->getOwnerId();}}if (highestPriority == priority) {// Switch back owner if the incoming client has the highest priority, as it is MRUhighestPriorityOwner = owner;}// Build eviction list of clients to remove//創建eviction list,這個隊列就是存在沖突的clientfor (const auto& i : mClients) {const KEY& curKey = i->getKey();int32_t curCost = i->getCost();ClientPriority curPriority = i->getPriority();int32_t curOwner = i->getOwnerId();// 判斷是否沖突://1.camera id 相同,存在沖突//isConflicting檢查底層是否存在沖突bool conflicting = (curKey == key || i->isConflicting(key) ||client->isConflicting(curKey));if (!returnIncompatibleClients) { //默認returnIncompatibleClients=false// Find evicted clients//查找沖突clientif (conflicting && curPriority < priority) {// Pre-existing conflicting client with higher priority exists//之前存在的client具有較高優先級,在將當前client添加到evictList中,//表示當前clieng不能打開相機evictList.clear();evictList.push_back(client);return evictList;} else if (conflicting || ((totalCost > mMaxCost && curCost > 0) &&(curPriority >= priority) &&!(highestPriorityOwner == owner && owner == curOwner))) {//在滿足下邊的條件時,將正在使用相機的client添加到evictList,表示在打開當前相機時,//正在使用相機的client因為和正在打開相機的client沖突需要關閉正在使用相機的client使用的相機。//1)存在沖突,且正在使用相機的client優先級低//2) 不存在沖突,但是totalCost 大于最大允許值mMaxCost //在當滿足如下條件時也需要將正在使用相機的client添加到evictList://1.如果正在打開相機的client和正在使用相機的client不是同一進程而且//正在打開相機的client優先級高于或者等于正在使用相機的client//2.如果正在打開相機的client和正在使用相機的client是同一進程//但是該進程不是最高優先級。// Add a pre-existing client to the eviction list if:// - We are adding a client with higher priority that conflicts with this one.// - The total cost including the incoming client's is more than the allowable// maximum, and the client has a non-zero cost, lower priority, and a different// owner than the incoming client when the incoming client has the// highest priority.evictList.push_back(i);totalCost -= curCost;}} else {// Find clients preventing the incoming client from being added// 這個條件上一步已經涵蓋了if (curPriority < priority && (conflicting || (totalCost > mMaxCost && curCost > 0))) {// Pre-existing conflicting client with higher priority existsevictList.push_back(i);}}}// Immediately return the incompatible clients if we are calculating these insteadif (returnIncompatibleClients) {return evictList;}// If the total cost is too high, return the input unless the input has the highest priority//如果經過上一步檢測,totalCost還是超過最大允許值且當前client不具有最高優先級,則將當前client添加到evictList,//表示當前client不能打開相機if (totalCost > mMaxCost && highestPriorityOwner != owner) {evictList.clear();evictList.push_back(client);return evictList;}return evictList;}4、分析getCameraState
std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(const String8& cameraId) const {std::shared_ptr<CameraState> state;{Mutex::Autolock lock(mCameraStatesLock);auto iter = mCameraStates.find(cameraId);if (iter != mCameraStates.end()) {state = iter->second;}}return state; }mCameraStates的賦值時在CameraService::enumerateProviders(),
主要是 mCameraStates.emplace(id8, std::make_shared(id8, cost.resourceCost, conflicting));
就是從HAL層獲取,cameraid為id8的相機的resourceCost和conflicting列表(和那些相機存在沖突)
至此分析完成,可以得到的結論是:
多進程可以在滿足一定條件是能都同時打開相機,需要滿足的條件有:
evictList為空且totalCost <= mMaxCost.
如果totalCost <= mMaxCost不成立,可以適當調大mMaxCost。如果evictList不為空,則可能需要調劑下進程優先級或者在cameraservice中強制改下進程優先級
總結
以上是生活随笔為你收集整理的Android 多进程同时打开相机的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 激光原理及其应用
- 下一篇: fatal: 无法访问 ‘‘github