blob: 20bd5e4479200ac4567973962e5b4d94329d140d [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080031#include <android/hardware/ICamera.h>
32#include <android/hardware/ICameraClient.h>
33
Alex Deymo9c2a2c22016-08-25 11:59:14 -070034#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080035#include <android-base/parseint.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080036#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryBase.h>
40#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080041#include <binder/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070043#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080044#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <hardware/hardware.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070046#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080048#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070050#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <utils/Errors.h>
52#include <utils/Log.h>
53#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080054#include <utils/Trace.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080055#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080056#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070057#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080058
Ruben Brunkb2119af2014-05-09 19:57:56 -070059#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060
61#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070062#include "api1/CameraClient.h"
63#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070064#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070065#include "utils/CameraTraces.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080067namespace {
68 const char* kPermissionServiceName = "permission";
69}; // namespace anonymous
70
Mathias Agopian65ab4712010-07-14 17:59:35 -070071namespace android {
72
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080073using binder::Status;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080074using hardware::ICamera;
75using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070076using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080077using hardware::ICameraServiceListener;
78using hardware::camera::common::V1_0::CameraDeviceStatus;
79using hardware::camera::common::V1_0::TorchModeStatus;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080080
Mathias Agopian65ab4712010-07-14 17:59:35 -070081// ----------------------------------------------------------------------------
82// Logging support -- this is for debugging only
83// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070084volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070085
Steve Blockb8a80522011-12-20 16:23:08 +000086#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
87#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
89static void setLogLevel(int level) {
90 android_atomic_write(level, &gLogLevel);
91}
92
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080093// Convenience methods for constructing binder::Status objects for error returns
94
95#define STATUS_ERROR(errorCode, errorString) \
96 binder::Status::fromServiceSpecificError(errorCode, \
97 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
98
99#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
100 binder::Status::fromServiceSpecificError(errorCode, \
101 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
102 __VA_ARGS__))
103
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104// ----------------------------------------------------------------------------
105
Igor Murashkincba2c162013-03-20 15:56:31 -0700106extern "C" {
107static void camera_device_status_change(
108 const struct camera_module_callbacks* callbacks,
109 int camera_id,
110 int new_status) {
111 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -0800112 static_cast<const CameraService*>(callbacks));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800113 String8 id = String8::format("%d", camera_id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700114
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800115 CameraDeviceStatus newStatus{CameraDeviceStatus::NOT_PRESENT};
116 switch (new_status) {
117 case CAMERA_DEVICE_STATUS_NOT_PRESENT:
118 newStatus = CameraDeviceStatus::NOT_PRESENT;
119 break;
120 case CAMERA_DEVICE_STATUS_PRESENT:
121 newStatus = CameraDeviceStatus::PRESENT;
122 break;
123 case CAMERA_DEVICE_STATUS_ENUMERATING:
124 newStatus = CameraDeviceStatus::ENUMERATING;
125 break;
126 default:
127 ALOGW("Unknown device status change to %d", new_status);
128 break;
129 }
130 cs->onDeviceStatusChanged(id, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700131}
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800132
133static void torch_mode_status_change(
134 const struct camera_module_callbacks* callbacks,
135 const char* camera_id,
136 int new_status) {
137 if (!callbacks || !camera_id) {
138 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
139 callbacks, camera_id);
140 }
141 sp<CameraService> cs = const_cast<CameraService*>(
142 static_cast<const CameraService*>(callbacks));
143
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800144 TorchModeStatus status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800145 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800146 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800147 status = TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800148 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800149 case TORCH_MODE_STATUS_AVAILABLE_OFF:
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800150 status = TorchModeStatus::AVAILABLE_OFF;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800151 break;
152 case TORCH_MODE_STATUS_AVAILABLE_ON:
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800153 status = TorchModeStatus::AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800154 break;
155 default:
156 ALOGE("Unknown torch status %d", new_status);
157 return;
158 }
159
160 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800161 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800162 status);
163}
Igor Murashkincba2c162013-03-20 15:56:31 -0700164} // extern "C"
165
Mathias Agopian65ab4712010-07-14 17:59:35 -0700166// ----------------------------------------------------------------------------
167
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800168CameraService::CameraService() :
169 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800170 mNumberOfCameras(0), mNumberOfNormalCameras(0),
Emilian Peevf53f66e2017-04-11 14:29:43 +0100171 mSoundRef(0), mInitialized(false) {
Steve Blockdf64d152012-01-04 20:05:49 +0000172 ALOGI("CameraService started (pid=%d)", getpid());
Igor Murashkinbfc99152013-02-27 12:55:20 -0800173
Igor Murashkincba2c162013-03-20 15:56:31 -0700174 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800175 this->torch_mode_status_change = android::torch_mode_status_change;
176
Ruben Brunkcc776712015-02-17 20:18:47 -0800177 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178}
179
Iliyan Malchev8951a972011-04-14 16:55:59 -0700180void CameraService::onFirstRef()
181{
Ruben Brunkcc776712015-02-17 20:18:47 -0800182 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800183
Iliyan Malchev8951a972011-04-14 16:55:59 -0700184 BnCameraService::onFirstRef();
185
Ruben Brunk99e69712015-05-26 17:25:07 -0700186 // Update battery life tracking if service is restarting
187 BatteryNotifier& notifier(BatteryNotifier::getInstance());
188 notifier.noteResetCamera();
189 notifier.noteResetFlashlight();
190
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800191 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800192
Emilian Peevf53f66e2017-04-11 14:29:43 +0100193 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800194 if (res == OK) {
195 mInitialized = true;
196 }
197
198 CameraService::pingCameraServiceProxy();
199}
200
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800201status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800202 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100203 Mutex::Autolock l(mServiceLock);
204
205 if (nullptr == mCameraProviderManager.get()) {
206 mCameraProviderManager = new CameraProviderManager();
207 res = mCameraProviderManager->initialize(this);
208 if (res != OK) {
209 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
210 __FUNCTION__, strerror(-res), res);
211 return res;
212 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800213 }
214
215 mNumberOfCameras = mCameraProviderManager->getCameraCount();
Emilian Peevf53f66e2017-04-11 14:29:43 +0100216 mNumberOfNormalCameras =
217 mCameraProviderManager->getAPI1CompatibleCameraCount();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800218
Yin-Chia Yeh067428c2017-01-13 15:19:24 -0800219 // Setup vendor tags before we call get_camera_info the first time
220 // because HAL might need to setup static vendor keys in get_camera_info
221 // TODO: maybe put this into CameraProviderManager::initialize()?
222 mCameraProviderManager->setUpVendorTags();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223
Emilian Peevaee727d2017-05-04 16:35:48 +0100224 if (nullptr == mFlashlight.get()) {
225 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
226 }
227
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800228 res = mFlashlight->findFlashUnits();
229 if (res != OK) {
230 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
231 }
232
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800233 for (auto& cameraId : mCameraProviderManager->getCameraDeviceIds()) {
Emilian Peevaee727d2017-05-04 16:35:48 +0100234 String8 id8 = String8(cameraId.c_str());
Yin-Chia Yehfad32282017-06-27 19:04:48 -0700235 bool cameraFound = false;
Emilian Peevaee727d2017-05-04 16:35:48 +0100236 {
Yin-Chia Yehfad32282017-06-27 19:04:48 -0700237
Emilian Peevaee727d2017-05-04 16:35:48 +0100238 Mutex::Autolock lock(mCameraStatesLock);
239 auto iter = mCameraStates.find(id8);
240 if (iter != mCameraStates.end()) {
Yin-Chia Yehfad32282017-06-27 19:04:48 -0700241 cameraFound = true;
Emilian Peevaee727d2017-05-04 16:35:48 +0100242 }
243 }
244
Yin-Chia Yehfad32282017-06-27 19:04:48 -0700245 if (!cameraFound) {
246 hardware::camera::common::V1_0::CameraResourceCost cost;
247 res = mCameraProviderManager->getResourceCost(cameraId, &cost);
248 if (res != OK) {
249 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
250 continue;
251 }
252 std::set<String8> conflicting;
253 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
254 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
255 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800256
Yin-Chia Yehfad32282017-06-27 19:04:48 -0700257 {
258 Mutex::Autolock lock(mCameraStatesLock);
259 mCameraStates.emplace(id8,
260 std::make_shared<CameraState>(id8, cost.resourceCost, conflicting));
261 }
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700262 }
263
264 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800265
266 if (mFlashlight->hasFlashUnit(id8)) {
Emilian Peevaee727d2017-05-04 16:35:48 +0100267 mTorchStatusMap.add(id8, TorchModeStatus::AVAILABLE_OFF);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800268 }
269 }
270
271 return OK;
272}
273
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700274sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800275 sp<ICameraServiceProxy> proxyBinder = nullptr;
276#ifndef __BRILLO__
Ruben Brunk2823ce02015-05-19 17:25:13 -0700277 sp<IServiceManager> sm = defaultServiceManager();
Eino-Ville Talvalaf4db13d2016-12-08 11:20:51 -0800278 // Use checkService because cameraserver normally starts before the
279 // system server and the proxy service. So the long timeout that getService
280 // has before giving up is inappropriate.
281 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800282 if (binder != nullptr) {
283 proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700284 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800285#endif
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700286 return proxyBinder;
287}
288
289void CameraService::pingCameraServiceProxy() {
290 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
291 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700292 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700293}
294
Mathias Agopian65ab4712010-07-14 17:59:35 -0700295CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800296 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700297}
298
Emilian Peevaee727d2017-05-04 16:35:48 +0100299void CameraService::onNewProviderRegistered() {
300 enumerateProviders();
301}
302
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800303void CameraService::onDeviceStatusChanged(const String8& id,
304 CameraDeviceStatus newHalStatus) {
305 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
306 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700307
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800308 StatusInternal newStatus = mapToInternal(newHalStatus);
309
Ruben Brunkcc776712015-02-17 20:18:47 -0800310 std::shared_ptr<CameraState> state = getCameraState(id);
311
312 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700313 if (newStatus == StatusInternal::PRESENT) {
314 ALOGW("%s: Unknown camera ID %s, probably newly registered?",
315 __FUNCTION__, id.string());
316 } else {
317 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
318 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700319 return;
320 }
321
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800322 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800323
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800324 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800325 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700326 return;
327 }
328
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800329 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700330 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
331 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800332 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700333 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800334 // Don't do this in updateStatus to avoid deadlock over mServiceLock
335 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700336
Ruben Brunkcc776712015-02-17 20:18:47 -0800337 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
338 // to this device until the status changes
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800339 updateStatus(StatusInternal::NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700340
Ruben Brunkcc776712015-02-17 20:18:47 -0800341 // Remove cached shim parameters
342 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700343
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700344 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800345 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700346 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800347
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700348 // Disconnect client
349 if (clientToDisconnect.get() != nullptr) {
350 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
351 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800352 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800353 clientToDisconnect->notifyError(
354 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800355 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800356 // Ensure not in binder RPC so client disconnect PID checks work correctly
357 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
358 "onDeviceStatusChanged must be called from the camera service process!");
359 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700360 }
361
Ruben Brunkcc776712015-02-17 20:18:47 -0800362 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800363 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700364 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
365 newStatus));
366 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800367 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700368 }
369
Igor Murashkincba2c162013-03-20 15:56:31 -0700370}
371
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800372void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800373 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800374 Mutex::Autolock al(mTorchStatusMutex);
375 onTorchStatusChangedLocked(cameraId, newStatus);
376}
377
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800378void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800379 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800380 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
381 __FUNCTION__, cameraId.string(), newStatus);
382
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800383 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800384 status_t res = getTorchStatusLocked(cameraId, &status);
385 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700386 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
387 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800388 return;
389 }
390 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800391 return;
392 }
393
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800394 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800395 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800396 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
397 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800398 return;
399 }
400
Ruben Brunkcc776712015-02-17 20:18:47 -0800401 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700402 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700403 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700404 auto iter = mTorchUidMap.find(cameraId);
405 if (iter != mTorchUidMap.end()) {
406 int oldUid = iter->second.second;
407 int newUid = iter->second.first;
408 BatteryNotifier& notifier(BatteryNotifier::getInstance());
409 if (oldUid != newUid) {
410 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800411 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700412 notifier.noteFlashlightOff(cameraId, oldUid);
413 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800414 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700415 notifier.noteFlashlightOn(cameraId, newUid);
416 }
417 iter->second.second = newUid;
418 } else {
419 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800420 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700421 notifier.noteFlashlightOn(cameraId, oldUid);
422 } else {
423 notifier.noteFlashlightOff(cameraId, oldUid);
424 }
425 }
426 }
427 }
428
429 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800430 Mutex::Autolock lock(mStatusListenerLock);
431 for (auto& i : mListenerList) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800432 i->onTorchStatusChanged(mapToInterface(newStatus), String16{cameraId});
Ruben Brunkcc776712015-02-17 20:18:47 -0800433 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800434 }
435}
436
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800437Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700438 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100439 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700440 switch (type) {
441 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800442 *numCameras = mNumberOfNormalCameras;
443 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700444 case CAMERA_TYPE_ALL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800445 *numCameras = mNumberOfCameras;
446 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700447 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800448 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700449 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800450 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
451 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700452 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800453 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454}
455
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800456Status CameraService::getCameraInfo(int cameraId,
457 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700458 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100459 Mutex::Autolock l(mServiceLock);
460
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800461 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800462 return STATUS_ERROR(ERROR_DISCONNECTED,
463 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700464 }
465
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800467 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
468 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 }
470
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800471 Status ret = Status::ok();
Emilian Peevf53f66e2017-04-11 14:29:43 +0100472 status_t err = mCameraProviderManager->getCameraInfo(std::to_string(cameraId), cameraInfo);
473 if (err != OK) {
474 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
475 "Error retrieving camera info from device %d: %s (%d)", cameraId,
476 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800477 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100478
Ruben Brunkcc776712015-02-17 20:18:47 -0800479 return ret;
480}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700481
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800482int CameraService::cameraIdToInt(const String8& cameraId) {
483 int id;
484 bool success = base::ParseInt(cameraId.string(), &id, 0);
485 if (!success) {
486 return -1;
487 }
488 return id;
489}
490
491Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800492 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700493 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700494 if (!cameraInfo) {
495 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800496 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700497 }
498
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800499 if (!mInitialized) {
500 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800501 return STATUS_ERROR(ERROR_DISCONNECTED,
502 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700503 }
504
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800505 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800506
Emilian Peevf53f66e2017-04-11 14:29:43 +0100507 status_t res = mCameraProviderManager->getCameraCharacteristics(
508 String8(cameraId).string(), cameraInfo);
509 if (res != OK) {
510 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
511 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
512 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700513 }
Zhijun He2b59be82013-09-25 10:14:30 -0700514
515 return ret;
516}
517
Ruben Brunkcc776712015-02-17 20:18:47 -0800518int CameraService::getCallingPid() {
519 return IPCThreadState::self()->getCallingPid();
520}
521
522int CameraService::getCallingUid() {
523 return IPCThreadState::self()->getCallingUid();
524}
525
526String8 CameraService::getFormattedCurrentTime() {
527 time_t now = time(nullptr);
528 char formattedTime[64];
529 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
530 return String8(formattedTime);
531}
532
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800533Status CameraService::getCameraVendorTagDescriptor(
534 /*out*/
535 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700536 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800537 if (!mInitialized) {
538 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800539 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800540 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800541 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
542 if (globalDescriptor != nullptr) {
543 *desc = *(globalDescriptor.get());
544 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800545 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800546}
547
Emilian Peev71c73a22017-03-21 16:35:51 +0000548Status CameraService::getCameraVendorTagCache(
549 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
550 ATRACE_CALL();
551 if (!mInitialized) {
552 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
553 return STATUS_ERROR(ERROR_DISCONNECTED,
554 "Camera subsystem not available");
555 }
556 sp<VendorTagDescriptorCache> globalCache =
557 VendorTagDescriptorCache::getGlobalVendorTagCache();
558 if (globalCache != nullptr) {
559 *cache = *(globalCache.get());
560 }
561 return Status::ok();
562}
563
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800564int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700565 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800566
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800567 int deviceVersion = 0;
568
Emilian Peevf53f66e2017-04-11 14:29:43 +0100569 status_t res;
570 hardware::hidl_version maxVersion{0,0};
571 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
572 &maxVersion);
573 if (res != OK) return -1;
574 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800575
Emilian Peevf53f66e2017-04-11 14:29:43 +0100576 hardware::CameraInfo info;
577 if (facing) {
578 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800579 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100580 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800581 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100582
Igor Murashkin634a5152013-02-20 17:15:11 -0800583 return deviceVersion;
584}
585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800586Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700587 switch(err) {
588 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800589 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800590 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800591 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
592 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800593 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800594 return STATUS_ERROR(ERROR_DISCONNECTED,
595 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700596 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800597 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
598 "Camera HAL encountered error %d: %s",
599 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700600 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800601}
602
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800603Status CameraService::makeClient(const sp<CameraService>& cameraService,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800604 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800605 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
606 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
607 /*out*/sp<BasicClient>* client) {
608
Ruben Brunkcc776712015-02-17 20:18:47 -0800609 if (halVersion < 0 || halVersion == deviceVersion) {
610 // Default path: HAL version is unspecified by caller, create CameraClient
611 // based on device version reported by the HAL.
612 switch(deviceVersion) {
613 case CAMERA_DEVICE_API_VERSION_1_0:
614 if (effectiveApiLevel == API_1) { // Camera1 API route
615 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800616 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
617 facing, clientPid, clientUid, getpid(), legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800618 } else { // Camera2 API route
619 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800620 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800621 "Camera device \"%s\" HAL version %d does not support camera2 API",
622 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800623 }
624 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800625 case CAMERA_DEVICE_API_VERSION_3_0:
626 case CAMERA_DEVICE_API_VERSION_3_1:
627 case CAMERA_DEVICE_API_VERSION_3_2:
628 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700629 case CAMERA_DEVICE_API_VERSION_3_4:
Ruben Brunkcc776712015-02-17 20:18:47 -0800630 if (effectiveApiLevel == API_1) { // Camera1 API route
631 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800632 *client = new Camera2Client(cameraService, tmp, packageName, cameraIdToInt(cameraId),
633 facing, clientPid, clientUid, servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800634 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800635 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
636 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
637 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800638 facing, clientPid, clientUid, servicePid);
639 }
640 break;
641 default:
642 // Should not be reachable
643 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800644 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800645 "Camera device \"%s\" has unknown HAL version %d",
646 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800647 }
648 } else {
649 // A particular HAL version is requested by caller. Create CameraClient
650 // based on the requested HAL version.
651 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
652 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
653 // Only support higher HAL version device opened as HAL1.0 device.
654 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800655 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
656 facing, clientPid, clientUid, servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800657 } else {
658 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
659 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
660 " opened as HAL %x device", halVersion, deviceVersion,
661 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800662 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800663 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
664 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800665 }
666 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800667 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800668}
669
Ruben Brunk6267b532015-04-30 17:44:07 -0700670String8 CameraService::toString(std::set<userid_t> intSet) {
671 String8 s("");
672 bool first = true;
673 for (userid_t i : intSet) {
674 if (first) {
675 s.appendFormat("%d", i);
676 first = false;
677 } else {
678 s.appendFormat(", %d", i);
679 }
680 }
681 return s;
682}
683
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800684int32_t CameraService::mapToInterface(TorchModeStatus status) {
685 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
686 switch (status) {
687 case TorchModeStatus::NOT_AVAILABLE:
688 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
689 break;
690 case TorchModeStatus::AVAILABLE_OFF:
691 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
692 break;
693 case TorchModeStatus::AVAILABLE_ON:
694 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
695 break;
696 default:
697 ALOGW("Unknown new flash status: %d", status);
698 }
699 return serviceStatus;
700}
701
702CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
703 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
704 switch (status) {
705 case CameraDeviceStatus::NOT_PRESENT:
706 serviceStatus = StatusInternal::NOT_PRESENT;
707 break;
708 case CameraDeviceStatus::PRESENT:
709 serviceStatus = StatusInternal::PRESENT;
710 break;
711 case CameraDeviceStatus::ENUMERATING:
712 serviceStatus = StatusInternal::ENUMERATING;
713 break;
714 default:
715 ALOGW("Unknown new HAL device status: %d", status);
716 }
717 return serviceStatus;
718}
719
720int32_t CameraService::mapToInterface(StatusInternal status) {
721 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
722 switch (status) {
723 case StatusInternal::NOT_PRESENT:
724 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
725 break;
726 case StatusInternal::PRESENT:
727 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
728 break;
729 case StatusInternal::ENUMERATING:
730 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
731 break;
732 case StatusInternal::NOT_AVAILABLE:
733 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
734 break;
735 case StatusInternal::UNKNOWN:
736 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
737 break;
738 default:
739 ALOGW("Unknown new internal device status: %d", status);
740 }
741 return serviceStatus;
742}
743
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800744Status CameraService::initializeShimMetadata(int cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800745 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700746
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800747 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800748 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800749 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800750 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800751 if (!(ret = connectHelper<ICameraClient,Client>(
752 sp<ICameraClient>{nullptr}, id, static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
753 internalPackageName, uid, USE_CALLING_PID,
754 API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
755 /*out*/ tmp)
756 ).isOk()) {
757 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700758 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800759 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700760}
761
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800762Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700763 /*out*/
764 CameraParameters* parameters) {
765
766 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
767
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800768 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700769
770 if (parameters == NULL) {
771 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800772 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700773 }
774
Ruben Brunkcc776712015-02-17 20:18:47 -0800775 String8 id = String8::format("%d", cameraId);
776
777 // Check if we already have parameters
778 {
779 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700780 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800781 auto cameraState = getCameraState(id);
782 if (cameraState == nullptr) {
783 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800784 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
785 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800786 }
787 CameraParameters p = cameraState->getShimParams();
788 if (!p.isEmpty()) {
789 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800790 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700791 }
792 }
793
Ruben Brunkcc776712015-02-17 20:18:47 -0800794 int64_t token = IPCThreadState::self()->clearCallingIdentity();
795 ret = initializeShimMetadata(cameraId);
796 IPCThreadState::self()->restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800797 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800798 // Error already logged by callee
799 return ret;
800 }
801
802 // Check for parameters again
803 {
804 // Scope for service lock
805 Mutex::Autolock lock(mServiceLock);
806 auto cameraState = getCameraState(id);
807 if (cameraState == nullptr) {
808 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800809 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
810 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700811 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800812 CameraParameters p = cameraState->getShimParams();
813 if (!p.isEmpty()) {
814 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800815 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700816 }
817 }
818
Ruben Brunkcc776712015-02-17 20:18:47 -0800819 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
820 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700822}
823
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800824// Can camera service trust the caller based on the calling UID?
825static bool isTrustedCallingUid(uid_t uid) {
826 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700827 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800828 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700829 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800830 return true;
831 default:
832 return false;
833 }
834}
835
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700837 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
838 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500839
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700840#ifdef __BRILLO__
841 UNUSED(clientName8);
842 UNUSED(clientUid);
843 UNUSED(clientPid);
844 UNUSED(originalClientPid);
845#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700846 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
847 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800848 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -0800849 return allowed;
850 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700851#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -0800852
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800853 int callingPid = getCallingPid();
854
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800855 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800856 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
857 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800858 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
859 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700860 }
861
Ruben Brunkcc776712015-02-17 20:18:47 -0800862 if (getCameraState(cameraId) == nullptr) {
863 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
864 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800865 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
866 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 }
868
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800869 status_t err = checkIfDeviceIsUsable(cameraId);
870 if (err != NO_ERROR) {
871 switch(err) {
872 case -ENODEV:
873 case -EBUSY:
874 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
875 "No camera device with ID \"%s\" currently available", cameraId.string());
876 default:
877 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
878 "Unknown error connecting to ID \"%s\"", cameraId.string());
879 }
880 }
881 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800882}
883
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800884Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700885 const String8& clientName8, int& clientUid, int& clientPid,
886 /*out*/int& originalClientPid) const {
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800887 int callingPid = getCallingPid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800888 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800890 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800892 clientUid = callingUid;
893 } else if (!isTrustedCallingUid(callingUid)) {
894 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
895 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800896 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
897 "Untrusted caller (calling PID %d, UID %d) trying to "
898 "forward camera access to camera %s for client %s (PID %d, UID %d)",
899 callingPid, callingUid, cameraId.string(),
900 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901 }
902
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800903 // Check if we can trust clientPid
904 if (clientPid == USE_CALLING_PID) {
905 clientPid = callingPid;
906 } else if (!isTrustedCallingUid(callingUid)) {
907 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
908 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800909 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
910 "Untrusted caller (calling PID %d, UID %d) trying to "
911 "forward camera access to camera %s for client %s (PID %d, UID %d)",
912 callingPid, callingUid, cameraId.string(),
913 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800914 }
915
916 // If it's not calling from cameraserver, check the permission.
917 if (callingPid != getpid() &&
918 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
919 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
921 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
922 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800923 }
924
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700925 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
926 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700927 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700928 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929
Ruben Brunk6267b532015-04-30 17:44:07 -0700930 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800931
Ruben Brunka8ca9152015-04-07 14:23:40 -0700932 // Only allow clients who are being used by the current foreground device user, unless calling
933 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700934 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
935 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
936 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
937 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800938 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
939 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
940 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700941 }
942
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800944}
945
946status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
947 auto cameraState = getCameraState(cameraId);
948 int callingPid = getCallingPid();
949 if (cameraState == nullptr) {
950 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
951 cameraId.string());
952 return -ENODEV;
953 }
954
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800955 StatusInternal currentStatus = cameraState->getStatus();
956 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
958 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700959 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800960 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
962 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700963 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700964 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700965
Ruben Brunkcc776712015-02-17 20:18:47 -0800966 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800967}
968
Ruben Brunkcc776712015-02-17 20:18:47 -0800969void CameraService::finishConnectLocked(const sp<BasicClient>& client,
970 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800971
Ruben Brunkcc776712015-02-17 20:18:47 -0800972 // Make a descriptor for the incoming client
973 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
974 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
975
976 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
977 String8(client->getPackageName()));
978
979 if (evicted.size() > 0) {
980 // This should never happen - clients should already have been removed in disconnect
981 for (auto& i : evicted) {
982 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
983 __FUNCTION__, i->getKey().string());
984 }
985
986 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
987 __FUNCTION__);
988 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700989
990 // And register a death notification for the client callback. Do
991 // this last to avoid Binder policy where a nested Binder
992 // transaction might be pre-empted to service the client death
993 // notification if the client process dies before linkToDeath is
994 // invoked.
995 sp<IBinder> remoteCallback = client->getRemote();
996 if (remoteCallback != nullptr) {
997 remoteCallback->linkToDeath(this);
998 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800999}
1000
1001status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1002 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1003 /*out*/
1004 sp<BasicClient>* client,
1005 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001006 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001007 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001008 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001009 DescriptorPtr clientDescriptor;
1010 {
1011 if (effectiveApiLevel == API_1) {
1012 // If we are using API1, any existing client for this camera ID with the same remote
1013 // should be returned rather than evicted to allow MediaRecorder to work properly.
1014
1015 auto current = mActiveClientManager.get(cameraId);
1016 if (current != nullptr) {
1017 auto clientSp = current->getValue();
1018 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001019 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1020 ALOGW("CameraService connect called from same client, but with a different"
1021 " API level, evicting prior client...");
1022 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001023 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001024 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001025 *client = clientSp;
1026 return NO_ERROR;
1027 }
1028 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001029 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001030 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001031
Ruben Brunkcc776712015-02-17 20:18:47 -08001032 // Get current active client PIDs
1033 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1034 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001035
Emilian Peev8131a262017-02-01 12:33:43 +00001036 std::vector<int> priorityScores(ownerPids.size());
1037 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001038
Emilian Peev8131a262017-02-01 12:33:43 +00001039 // Get priority scores of all active PIDs
1040 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1041 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1042 /*out*/&priorityScores[0]);
1043 if (err != OK) {
1044 ALOGE("%s: Priority score query failed: %d",
1045 __FUNCTION__, err);
1046 return err;
1047 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001048
Ruben Brunkcc776712015-02-17 20:18:47 -08001049 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001050 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001052 pidToPriorityMap.emplace(ownerPids[i],
1053 resource_policy::ClientPriority(priorityScores[i], states[i]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001054 }
1055 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001056
Ruben Brunkcc776712015-02-17 20:18:47 -08001057 // Get state for the given cameraId
1058 auto state = getCameraState(cameraId);
1059 if (state == nullptr) {
1060 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1061 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001062 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001063 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001064 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001065
1066 // Make descriptor for incoming client
1067 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1068 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1069 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001070 priorityScores[priorityScores.size() - 1],
1071 clientPid,
1072 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001073
1074 // Find clients that would be evicted
1075 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1076
1077 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1078 // background, so we cannot do evictions
1079 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1080 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1081 " priority).", clientPid);
1082
1083 sp<BasicClient> clientSp = clientDescriptor->getValue();
1084 String8 curTime = getFormattedCurrentTime();
1085 auto incompatibleClients =
1086 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1087
1088 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001089 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001090 cameraId.string(), packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001091 priorityScores[priorityScores.size() - 1],
1092 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001093
1094 for (auto& i : incompatibleClients) {
1095 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001096 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1097 i->getKey().string(),
1098 String8{i->getValue()->getPackageName()}.string(),
1099 i->getOwnerId(), i->getPriority().getScore(),
1100 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001101 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001102 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001103 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001104 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001105 }
1106
1107 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001108 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001109 mEventLog.add(msg);
1110
1111 return -EBUSY;
1112 }
1113
1114 for (auto& i : evicted) {
1115 sp<BasicClient> clientSp = i->getValue();
1116 if (clientSp.get() == nullptr) {
1117 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1118
1119 // TODO: Remove this
1120 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1121 __FUNCTION__);
1122 mActiveClientManager.remove(i);
1123 continue;
1124 }
1125
1126 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1127 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001128 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001129
Ruben Brunkcc776712015-02-17 20:18:47 -08001130 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001131 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001132 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1133 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001135 i->getOwnerId(), i->getPriority().getScore(),
1136 i->getPriority().getState(), cameraId.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001137 packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001138 priorityScores[priorityScores.size() - 1],
1139 states[states.size() - 1]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001140
1141 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001142 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001144 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001145 }
1146
Ruben Brunkcc776712015-02-17 20:18:47 -08001147 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1148 // other clients from connecting in mServiceLockWrapper if held
1149 mServiceLock.unlock();
1150
1151 // Clear caller identity temporarily so client disconnect PID checks work correctly
1152 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1153
1154 // Destroy evicted clients
1155 for (auto& i : evictedClients) {
1156 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001157 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001158 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001159
1160 IPCThreadState::self()->restoreCallingIdentity(token);
1161
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001162 for (const auto& i : evictedClients) {
1163 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1164 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1165 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1166 if (ret == TIMED_OUT) {
1167 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1168 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1169 mActiveClientManager.toString().string());
1170 return -EBUSY;
1171 }
1172 if (ret != NO_ERROR) {
1173 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1174 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1175 ret, mActiveClientManager.toString().string());
1176 return ret;
1177 }
1178 }
1179
1180 evictedClients.clear();
1181
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 // Once clients have been disconnected, relock
1183 mServiceLock.lock();
1184
1185 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1186 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1187 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001188 }
1189
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 *partial = clientDescriptor;
1191 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001192}
1193
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001194Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001195 const sp<ICameraClient>& cameraClient,
1196 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001197 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001198 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001199 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001200 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001201 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001202
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001203 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001204 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001205 String8 id = String8::format("%d", cameraId);
1206 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001207 ret = connectHelper<ICameraClient,Client>(cameraClient, id,
1208 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1209 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1210 /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001211
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001212 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001213 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001214 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001215 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 }
1217
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001218 *device = client;
1219 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220}
1221
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001222Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001223 const sp<ICameraClient>& cameraClient,
1224 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001225 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001226 int clientUid,
1227 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001228 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001229
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001230 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001231 String8 id = String8::format("%d", cameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001232
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001233 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001234 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001235 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion,
1236 clientPackageName, clientUid, USE_CALLING_PID, API_1,
1237 /*legacyMode*/ true, /*shimUpdateOnly*/ false,
1238 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001239
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001240 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001241 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001243 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001244 }
1245
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001246 *device = client;
1247 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001248}
1249
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001250Status CameraService::connectDevice(
1251 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001252 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001253 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001254 int clientUid,
1255 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001256 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001257
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001258 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001259 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001260 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 sp<CameraDeviceClient> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001262 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1263 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
1264 clientUid, USE_CALLING_PID, API_2,
1265 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1266 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001267
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001268 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001269 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001270 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001271 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001272 }
1273
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001274 *device = client;
1275 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001276}
1277
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001278template<class CALLBACK, class CLIENT>
1279Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
1280 int halVersion, const String16& clientPackageName, int clientUid, int clientPid,
1281 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
1282 /*out*/sp<CLIENT>& device) {
1283 binder::Status ret = binder::Status::ok();
1284
1285 String8 clientName8(clientPackageName);
1286
1287 int originalClientPid = 0;
1288
1289 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1290 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1291 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1292 static_cast<int>(effectiveApiLevel));
1293
1294 sp<CLIENT> client = nullptr;
1295 {
1296 // Acquire mServiceLock and prevent other clients from connecting
1297 std::unique_ptr<AutoConditionLock> lock =
1298 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1299
1300 if (lock == nullptr) {
1301 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1302 , clientPid);
1303 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1304 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1305 cameraId.string(), clientName8.string(), clientPid);
1306 }
1307
1308 // Enforce client permissions and do basic sanity checks
1309 if(!(ret = validateConnectLocked(cameraId, clientName8,
1310 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1311 return ret;
1312 }
1313
1314 // Check the shim parameters after acquiring lock, if they have already been updated and
1315 // we were doing a shim update, return immediately
1316 if (shimUpdateOnly) {
1317 auto cameraState = getCameraState(cameraId);
1318 if (cameraState != nullptr) {
1319 if (!cameraState->getShimParams().isEmpty()) return ret;
1320 }
1321 }
1322
1323 status_t err;
1324
1325 sp<BasicClient> clientTmp = nullptr;
1326 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1327 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1328 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1329 /*out*/&partial)) != NO_ERROR) {
1330 switch (err) {
1331 case -ENODEV:
1332 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1333 "No camera device with ID \"%s\" currently available",
1334 cameraId.string());
1335 case -EBUSY:
1336 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1337 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1338 cameraId.string());
1339 default:
1340 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1341 "Unexpected error %s (%d) opening camera \"%s\"",
1342 strerror(-err), err, cameraId.string());
1343 }
1344 }
1345
1346 if (clientTmp.get() != nullptr) {
1347 // Handle special case for API1 MediaRecorder where the existing client is returned
1348 device = static_cast<CLIENT*>(clientTmp.get());
1349 return ret;
1350 }
1351
1352 // give flashlight a chance to close devices if necessary.
1353 mFlashlight->prepareDeviceOpen(cameraId);
1354
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001355 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001356 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001357 if (facing == -1) {
1358 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1359 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1360 "Unable to get camera device \"%s\" facing", cameraId.string());
1361 }
1362
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001363 sp<BasicClient> tmp = nullptr;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001364 if(!(ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001365 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
1366 /*out*/&tmp)).isOk()) {
1367 return ret;
1368 }
1369 client = static_cast<CLIENT*>(tmp.get());
1370
1371 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1372 __FUNCTION__);
1373
Emilian Peevf53f66e2017-04-11 14:29:43 +01001374 err = client->initialize(mCameraProviderManager);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001375 if (err != OK) {
1376 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001377 // Errors could be from the HAL module open call or from AppOpsManager
1378 switch(err) {
1379 case BAD_VALUE:
1380 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1381 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1382 case -EBUSY:
1383 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1384 "Camera \"%s\" is already open", cameraId.string());
1385 case -EUSERS:
1386 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1387 "Too many cameras already open, cannot open camera \"%s\"",
1388 cameraId.string());
1389 case PERMISSION_DENIED:
1390 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1391 "No permission to open camera \"%s\"", cameraId.string());
1392 case -EACCES:
1393 return STATUS_ERROR_FMT(ERROR_DISABLED,
1394 "Camera \"%s\" disabled by policy", cameraId.string());
1395 case -ENODEV:
1396 default:
1397 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1398 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1399 strerror(-err), err);
1400 }
1401 }
1402
1403 // Update shim paremeters for legacy clients
1404 if (effectiveApiLevel == API_1) {
1405 // Assume we have always received a Client subclass for API1
1406 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1407 String8 rawParams = shimClient->getParameters();
1408 CameraParameters params(rawParams);
1409
1410 auto cameraState = getCameraState(cameraId);
1411 if (cameraState != nullptr) {
1412 cameraState->setShimParams(params);
1413 } else {
1414 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1415 __FUNCTION__, cameraId.string());
1416 }
1417 }
1418
1419 if (shimUpdateOnly) {
1420 // If only updating legacy shim parameters, immediately disconnect client
1421 mServiceLock.unlock();
1422 client->disconnect();
1423 mServiceLock.lock();
1424 } else {
1425 // Otherwise, add client to active clients list
1426 finishConnectLocked(client, partial);
1427 }
1428 } // lock is destroyed, allow further connect calls
1429
1430 // Important: release the mutex here so the client can call back into the service from its
1431 // destructor (can be at the end of the call)
1432 device = client;
1433 return ret;
1434}
1435
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001436Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001437 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001438 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001439
1440 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001441 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001442 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001443 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1444 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001445 }
1446
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001447 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001448 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001449
1450 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001451 auto state = getCameraState(id);
1452 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001453 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001454 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1455 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001456 }
1457
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001458 StatusInternal cameraStatus = state->getStatus();
1459 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001460 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1461 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001462 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1463 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001464 }
1465
1466 {
1467 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001468 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 status_t err = getTorchStatusLocked(id, &status);
1470 if (err != OK) {
1471 if (err == NAME_NOT_FOUND) {
1472 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1473 "Camera \"%s\" does not have a flash unit", id.string());
1474 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001475 ALOGE("%s: getting current torch status failed for camera %s",
1476 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001477 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1478 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1479 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001480 }
1481
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001482 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001483 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001484 ALOGE("%s: torch mode of camera %s is not available because "
1485 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001486 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1487 "Torch for camera \"%s\" is not available due to an existing camera user",
1488 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001489 } else {
1490 ALOGE("%s: torch mode of camera %s is not available due to "
1491 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001492 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1493 "Torch for camera \"%s\" is not available due to insufficient resources",
1494 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001495 }
1496 }
1497 }
1498
Ruben Brunk99e69712015-05-26 17:25:07 -07001499 {
1500 // Update UID map - this is used in the torch status changed callbacks, so must be done
1501 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001502 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001503 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1504 mTorchUidMap[id].first = uid;
1505 mTorchUidMap[id].second = uid;
1506 } else {
1507 // Set the pending UID
1508 mTorchUidMap[id].first = uid;
1509 }
1510 }
1511
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001512 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001513
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001514 if (err != OK) {
1515 int32_t errorCode;
1516 String8 msg;
1517 switch (err) {
1518 case -ENOSYS:
1519 msg = String8::format("Camera \"%s\" has no flashlight",
1520 id.string());
1521 errorCode = ERROR_ILLEGAL_ARGUMENT;
1522 break;
1523 default:
1524 msg = String8::format(
1525 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1526 id.string(), enabled, strerror(-err), err);
1527 errorCode = ERROR_INVALID_OPERATION;
1528 }
1529 ALOGE("%s: %s", __FUNCTION__, msg.string());
1530 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001531 }
1532
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001533 {
1534 // update the link to client's death
1535 Mutex::Autolock al(mTorchClientMapMutex);
1536 ssize_t index = mTorchClientMap.indexOfKey(id);
1537 if (enabled) {
1538 if (index == NAME_NOT_FOUND) {
1539 mTorchClientMap.add(id, clientBinder);
1540 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001541 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001542 mTorchClientMap.replaceValueAt(index, clientBinder);
1543 }
1544 clientBinder->linkToDeath(this);
1545 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001546 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001547 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001548 }
1549
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001550 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001551}
1552
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001553Status CameraService::notifySystemEvent(int32_t eventId,
1554 const std::vector<int32_t>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001555 ATRACE_CALL();
1556
Ruben Brunk36597b22015-03-20 22:15:57 -07001557 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001558 case ICameraService::EVENT_USER_SWITCHED: {
1559 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001560 break;
1561 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001562 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001563 default: {
1564 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1565 eventId);
1566 break;
1567 }
1568 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001569 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001570}
1571
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001572Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1573 /*out*/
1574 std::vector<hardware::CameraStatus> *cameraStatuses) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001575 ATRACE_CALL();
1576
Igor Murashkinbfc99152013-02-27 12:55:20 -08001577 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001578
Ruben Brunk3450ba72015-06-16 11:00:37 -07001579 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001580 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001582 }
1583
Igor Murashkinbfc99152013-02-27 12:55:20 -08001584 Mutex::Autolock lock(mServiceLock);
1585
Ruben Brunkcc776712015-02-17 20:18:47 -08001586 {
1587 Mutex::Autolock lock(mStatusListenerLock);
1588 for (auto& it : mListenerList) {
1589 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1590 ALOGW("%s: Tried to add listener %p which was already subscribed",
1591 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001592 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001593 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001594 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001595
1596 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001597 }
1598
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001599 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001600 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001601 Mutex::Autolock lock(mCameraStatesLock);
1602 for (auto& i : mCameraStates) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001603 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001604 }
1605 }
1606
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001607 /*
1608 * Immediately signal current torch status to this listener only
1609 * This may be a subset of all the devices, so don't include it in the response directly
1610 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001611 {
1612 Mutex::Autolock al(mTorchStatusMutex);
1613 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001614 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001615 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001616 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001617 }
1618
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001620}
Ruben Brunkcc776712015-02-17 20:18:47 -08001621
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001622Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001623 ATRACE_CALL();
1624
Igor Murashkinbfc99152013-02-27 12:55:20 -08001625 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1626
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001627 if (listener == 0) {
1628 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001629 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001630 }
1631
Igor Murashkinbfc99152013-02-27 12:55:20 -08001632 Mutex::Autolock lock(mServiceLock);
1633
Ruben Brunkcc776712015-02-17 20:18:47 -08001634 {
1635 Mutex::Autolock lock(mStatusListenerLock);
1636 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1637 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1638 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001639 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001640 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001641 }
1642 }
1643
1644 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1645 __FUNCTION__, listener.get());
1646
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001647 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001648}
1649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001651
1652 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001653 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1654
1655 if (parameters == NULL) {
1656 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001658 }
1659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001660 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001661
1662 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001663 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001664 // Error logged by caller
1665 return ret;
1666 }
1667
1668 String8 shimParamsString8 = shimParams.flatten();
1669 String16 shimParamsString16 = String16(shimParamsString8);
1670
1671 *parameters = shimParamsString16;
1672
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001673 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001674}
1675
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001676Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1677 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001678 ATRACE_CALL();
1679
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001680 const String8 id = String8(cameraId);
1681
1682 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001683
1684 switch (apiVersion) {
1685 case API_VERSION_1:
1686 case API_VERSION_2:
1687 break;
1688 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001689 String8 msg = String8::format("Unknown API version %d", apiVersion);
1690 ALOGE("%s: %s", __FUNCTION__, msg.string());
1691 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001692 }
1693
Emilian Peev28ad2ea2017-02-07 16:14:32 +00001694 int deviceVersion = getDeviceVersion(id);
Igor Murashkin65d14b92014-06-17 12:03:20 -07001695 switch(deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001696 case CAMERA_DEVICE_API_VERSION_1_0:
1697 case CAMERA_DEVICE_API_VERSION_3_0:
1698 case CAMERA_DEVICE_API_VERSION_3_1:
1699 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001700 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1701 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001702 *isSupported = false;
1703 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001704 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1705 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001706 *isSupported = true;
1707 }
1708 break;
1709 case CAMERA_DEVICE_API_VERSION_3_2:
1710 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001711 case CAMERA_DEVICE_API_VERSION_3_4:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001712 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1713 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001714 *isSupported = true;
1715 break;
1716 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001717 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001718 ALOGE("%s: %s", __FUNCTION__, msg.string());
1719 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001720 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001721 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001722 String8 msg = String8::format("Unknown device version %x for device %s",
1723 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001724 ALOGE("%s: %s", __FUNCTION__, msg.string());
1725 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1726 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07001727 }
1728
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001729 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001730}
1731
Ruben Brunkcc776712015-02-17 20:18:47 -08001732void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001733 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001734 for (auto& i : mActiveClientManager.getAll()) {
1735 auto clientSp = i->getValue();
1736 if (clientSp.get() == client) {
1737 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001738 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001739 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001740}
1741
Ruben Brunkcc776712015-02-17 20:18:47 -08001742bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1743 const int callingPid = getCallingPid();
1744 const int servicePid = getpid();
1745 bool ret = false;
1746 {
1747 // Acquire mServiceLock and prevent other clients from connecting
1748 std::unique_ptr<AutoConditionLock> lock =
1749 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001750
Igor Murashkin634a5152013-02-20 17:15:11 -08001751
Ruben Brunkcc776712015-02-17 20:18:47 -08001752 std::vector<sp<BasicClient>> evicted;
1753 for (auto& i : mActiveClientManager.getAll()) {
1754 auto clientSp = i->getValue();
1755 if (clientSp.get() == nullptr) {
1756 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1757 mActiveClientManager.remove(i);
1758 continue;
1759 }
1760 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1761 callingPid == clientSp->getClientPid())) {
1762 mActiveClientManager.remove(i);
1763 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001764
Ruben Brunkcc776712015-02-17 20:18:47 -08001765 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001766 clientSp->notifyError(
1767 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001768 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001769 }
1770 }
1771
Ruben Brunkcc776712015-02-17 20:18:47 -08001772 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1773 // other clients from connecting in mServiceLockWrapper if held
1774 mServiceLock.unlock();
1775
Ruben Brunk36597b22015-03-20 22:15:57 -07001776 // Do not clear caller identity, remote caller should be client proccess
1777
Ruben Brunkcc776712015-02-17 20:18:47 -08001778 for (auto& i : evicted) {
1779 if (i.get() != nullptr) {
1780 i->disconnect();
1781 ret = true;
1782 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001783 }
1784
Ruben Brunkcc776712015-02-17 20:18:47 -08001785 // Reacquire mServiceLock
1786 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001787
Ruben Brunkcc776712015-02-17 20:18:47 -08001788 } // lock is destroyed, allow further connect calls
1789
1790 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001791}
1792
Ruben Brunkcc776712015-02-17 20:18:47 -08001793std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1794 const String8& cameraId) const {
1795 std::shared_ptr<CameraState> state;
1796 {
1797 Mutex::Autolock lock(mCameraStatesLock);
1798 auto iter = mCameraStates.find(cameraId);
1799 if (iter != mCameraStates.end()) {
1800 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 }
1802 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001803 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804}
1805
Ruben Brunkcc776712015-02-17 20:18:47 -08001806sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1807 // Remove from active clients list
1808 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1809 if (clientDescriptorPtr == nullptr) {
1810 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1811 cameraId.string());
1812 return sp<BasicClient>{nullptr};
1813 }
1814
1815 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001816}
1817
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001818void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001819 // Acquire mServiceLock and prevent other clients from connecting
1820 std::unique_ptr<AutoConditionLock> lock =
1821 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1822
Ruben Brunk6267b532015-04-30 17:44:07 -07001823 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001824 for (size_t i = 0; i < newUserIds.size(); i++) {
1825 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001826 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001827 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07001828 return;
1829 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001830 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001831 }
1832
Ruben Brunka8ca9152015-04-07 14:23:40 -07001833
Ruben Brunk6267b532015-04-30 17:44:07 -07001834 if (newAllowedUsers == mAllowedUsers) {
1835 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1836 return;
1837 }
1838
1839 logUserSwitch(mAllowedUsers, newAllowedUsers);
1840
1841 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001842
1843 // Current user has switched, evict all current clients.
1844 std::vector<sp<BasicClient>> evicted;
1845 for (auto& i : mActiveClientManager.getAll()) {
1846 auto clientSp = i->getValue();
1847
1848 if (clientSp.get() == nullptr) {
1849 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1850 continue;
1851 }
1852
Ruben Brunk6267b532015-04-30 17:44:07 -07001853 // Don't evict clients that are still allowed.
1854 uid_t clientUid = clientSp->getClientUid();
1855 userid_t clientUserId = multiuser_get_user_id(clientUid);
1856 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1857 continue;
1858 }
1859
Ruben Brunk36597b22015-03-20 22:15:57 -07001860 evicted.push_back(clientSp);
1861
1862 String8 curTime = getFormattedCurrentTime();
1863
1864 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1865 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001866
Ruben Brunk36597b22015-03-20 22:15:57 -07001867 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001868 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001869 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
1870 " to user switch.", i->getKey().string(),
1871 String8{clientSp->getPackageName()}.string(),
1872 i->getOwnerId(), i->getPriority().getScore(),
1873 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001874
1875 }
1876
1877 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1878 // blocking other clients from connecting in mServiceLockWrapper if held.
1879 mServiceLock.unlock();
1880
1881 // Clear caller identity temporarily so client disconnect PID checks work correctly
1882 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1883
1884 for (auto& i : evicted) {
1885 i->disconnect();
1886 }
1887
1888 IPCThreadState::self()->restoreCallingIdentity(token);
1889
1890 // Reacquire mServiceLock
1891 mServiceLock.lock();
1892}
Ruben Brunkcc776712015-02-17 20:18:47 -08001893
Ruben Brunka8ca9152015-04-07 14:23:40 -07001894void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001895 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001896 Mutex::Autolock l(mLogLock);
1897 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898}
1899
Ruben Brunka8ca9152015-04-07 14:23:40 -07001900void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001901 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001902 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001903 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001904 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001905}
1906
1907void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001908 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001909 // Log the clients evicted
1910 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001911 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001912}
1913
1914void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001915 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001916 // Log the client rejected
1917 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001918 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001919}
1920
Ruben Brunk6267b532015-04-30 17:44:07 -07001921void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1922 const std::set<userid_t>& newUserIds) {
1923 String8 newUsers = toString(newUserIds);
1924 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001925 if (oldUsers.size() == 0) {
1926 oldUsers = "<None>";
1927 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07001928 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001929 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07001930 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001931}
1932
1933void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1934 // Log the device removal
1935 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1936}
1937
1938void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1939 // Log the device removal
1940 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1941}
1942
1943void CameraService::logClientDied(int clientPid, const char* reason) {
1944 // Log the device removal
1945 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001946}
1947
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001948void CameraService::logServiceError(const char* msg, int errorCode) {
1949 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001950 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001951}
1952
Ruben Brunk36597b22015-03-20 22:15:57 -07001953status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1954 uint32_t flags) {
1955
1956 const int pid = getCallingPid();
1957 const int selfPid = getpid();
1958
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 // Permission checks
1960 switch (code) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001961 case BnCameraService::NOTIFYSYSTEMEVENT: {
Ruben Brunk36597b22015-03-20 22:15:57 -07001962 if (pid != selfPid) {
1963 // Ensure we're being called by system_server, or similar process with
1964 // permissions to notify the camera service about system events
1965 if (!checkCallingPermission(
1966 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1967 const int uid = getCallingUid();
1968 ALOGE("Permission Denial: cannot send updates to camera service about system"
1969 " events from pid=%d, uid=%d", pid, uid);
1970 return PERMISSION_DENIED;
1971 }
1972 }
1973 break;
1974 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 }
1976
1977 return BnCameraService::onTransact(code, data, reply, flags);
1978}
1979
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980// We share the media players for shutter and recording sound for all clients.
1981// A reference count is kept to determine when we will actually release the
1982// media players.
1983
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001984MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001986 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001987 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 mp->prepare();
1989 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001990 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991 return NULL;
1992 }
1993 return mp;
1994}
1995
1996void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001997 ATRACE_CALL();
1998
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 Mutex::Autolock lock(mSoundLock);
2000 LOG1("CameraService::loadSound ref=%d", mSoundRef);
2001 if (mSoundRef++) return;
2002
2003 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07002004 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
2005 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006}
2007
2008void CameraService::releaseSound() {
2009 Mutex::Autolock lock(mSoundLock);
2010 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
2011 if (--mSoundRef) return;
2012
2013 for (int i = 0; i < NUM_SOUNDS; i++) {
2014 if (mSoundPlayer[i] != 0) {
2015 mSoundPlayer[i]->disconnect();
2016 mSoundPlayer[i].clear();
2017 }
2018 }
2019}
2020
2021void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002022 ATRACE_CALL();
2023
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 LOG1("playSound(%d)", kind);
2025 Mutex::Autolock lock(mSoundLock);
2026 sp<MediaPlayer> player = mSoundPlayer[kind];
2027 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002028 player->seekTo(0);
2029 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 }
2031}
2032
2033// ----------------------------------------------------------------------------
2034
2035CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002036 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002037 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002038 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002039 int clientPid, uid_t clientUid,
2040 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002041 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002042 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002043 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002044 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002045 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002046 servicePid),
2047 mCameraId(CameraService::cameraIdToInt(cameraIdStr))
Igor Murashkin634a5152013-02-20 17:15:11 -08002048{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002050 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002052 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002055
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002056 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057}
2058
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059// tear down the client
2060CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002061 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002062 mDestructionStarted = true;
2063
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002064 sCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002065 // unconditionally disconnect. function is idempotent
2066 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067}
2068
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002069sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2070
Igor Murashkin634a5152013-02-20 17:15:11 -08002071CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002072 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002073 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002074 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002075 int clientPid, uid_t clientUid,
2076 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002077 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2078 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2079 mServicePid(servicePid),
2080 mDisconnected(false),
2081 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002082{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002083 if (sCameraService == nullptr) {
2084 sCameraService = cameraService;
2085 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002086 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002087 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002088
2089 // In some cases the calling code has no access to the package it runs under.
2090 // For example, NDK camera API.
2091 // In this case we will get the packages for the calling UID and pick the first one
2092 // for attributing the app op. This will work correctly for runtime permissions
2093 // as for legacy apps we will toggle the app op for all packages in the UID.
2094 // The caveat is that the operation may be attributed to the wrong package and
2095 // stats based on app ops may be slightly off.
2096 if (mClientPackageName.size() <= 0) {
2097 sp<IServiceManager> sm = defaultServiceManager();
2098 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2099 if (binder == 0) {
2100 ALOGE("Cannot get permission service");
2101 // Leave mClientPackageName unchanged (empty) and the further interaction
2102 // with camera will fail in BasicClient::startCameraOps
2103 return;
2104 }
2105
2106 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2107 Vector<String16> packages;
2108
2109 permCtrl->getPackagesForUid(mClientUid, packages);
2110
2111 if (packages.isEmpty()) {
2112 ALOGE("No packages for calling UID");
2113 // Leave mClientPackageName unchanged (empty) and the further interaction
2114 // with camera will fail in BasicClient::startCameraOps
2115 return;
2116 }
2117 mClientPackageName = packages[0];
2118 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002119}
2120
2121CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002122 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002123 mDestructionStarted = true;
2124}
2125
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002126binder::Status CameraService::BasicClient::disconnect() {
2127 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002128 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002129 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002130 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002131 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002132
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002133 sCameraService->removeByClient(this);
2134 sCameraService->logDisconnected(mCameraIdStr, mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002135 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08002136
2137 sp<IBinder> remote = getRemote();
2138 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002139 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002140 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002141
2142 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002143 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002144 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2145 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2146 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002147
Igor Murashkincba2c162013-03-20 15:56:31 -07002148 // client shouldn't be able to call into us anymore
2149 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002150
2151 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002152}
2153
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002154status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2155 // No dumping of clients directly over Binder,
2156 // must go through CameraService::dump
2157 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2158 IPCThreadState::self()->getCallingUid(), NULL, 0);
2159 return OK;
2160}
2161
Ruben Brunkcc776712015-02-17 20:18:47 -08002162String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002163 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002164}
2165
2166
2167int CameraService::BasicClient::getClientPid() const {
2168 return mClientPid;
2169}
2170
Ruben Brunk6267b532015-04-30 17:44:07 -07002171uid_t CameraService::BasicClient::getClientUid() const {
2172 return mClientUid;
2173}
2174
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002175bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2176 // Defaults to API2.
2177 return level == API_2;
2178}
2179
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002180status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002181 ATRACE_CALL();
2182
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002183 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002184 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002185 mOpsCallback = new OpsCallback(this);
2186
Igor Murashkine6800ce2013-03-04 17:25:57 -08002187 {
2188 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002189 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002190 }
2191
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002192 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002193 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002194 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002195 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002196
Svetoslav28e8ef72015-05-11 19:21:31 -07002197 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002198 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2199 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002200 return PERMISSION_DENIED;
2201 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002202
Svetoslav28e8ef72015-05-11 19:21:31 -07002203 if (res == AppOpsManager::MODE_IGNORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002204 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2205 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002206 // Return the same error as for device policy manager rejection
2207 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002208 }
2209
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002210 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002211
2212 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002213 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002214
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002215 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002216 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07002217 mCameraIdStr, mCameraFacing, mClientPackageName);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002218
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002219 return OK;
2220}
2221
2222status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002223 ATRACE_CALL();
2224
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002225 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002226 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002227 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002228 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002229 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002230 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002231
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002232 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
2233 StatusInternal::ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002234
Ruben Brunkcc776712015-02-17 20:18:47 -08002235 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002236 sCameraService->updateStatus(StatusInternal::PRESENT,
2237 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002238
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002239 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002240 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07002241 mCameraIdStr, mCameraFacing, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002242 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002243 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002244 if (mOpsCallback != NULL) {
2245 mAppOpsManager.stopWatchingMode(mOpsCallback);
2246 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002247 mOpsCallback.clear();
2248
2249 return OK;
2250}
2251
2252void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002253 ATRACE_CALL();
2254
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002255 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002256 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002257
2258 if (op != AppOpsManager::OP_CAMERA) {
2259 ALOGW("Unexpected app ops notification received: %d", op);
2260 return;
2261 }
2262
2263 int32_t res;
2264 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002265 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002266 ALOGV("checkOp returns: %d, %s ", res,
2267 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2268 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2269 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2270 "UNKNOWN");
2271
2272 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002273 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002274 myName.string());
2275 // Reset the client PID to allow server-initiated disconnect,
2276 // and to prevent further calls by client.
2277 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002278 CaptureResultExtras resultExtras; // a dummy result (invalid)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002279 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002280 disconnect();
2281 }
2282}
2283
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284// ----------------------------------------------------------------------------
2285
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002286void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002287 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002288 (void) errorCode;
2289 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002290 if (mRemoteCallback != NULL) {
2291 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2292 } else {
2293 ALOGE("mRemoteCallback is NULL!!");
2294 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002295}
2296
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002297// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002299 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002300 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002301}
2302
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002303bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2304 return level == API_1;
2305}
2306
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002307CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2308 mClient(client) {
2309}
2310
2311void CameraService::Client::OpsCallback::opChanged(int32_t op,
2312 const String16& packageName) {
2313 sp<BasicClient> client = mClient.promote();
2314 if (client != NULL) {
2315 client->opChanged(op, packageName);
2316 }
2317}
2318
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002320// CameraState
2321// ----------------------------------------------------------------------------
2322
2323CameraService::CameraState::CameraState(const String8& id, int cost,
2324 const std::set<String8>& conflicting) : mId(id),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002325 mStatus(StatusInternal::PRESENT), mCost(cost), mConflicting(conflicting) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08002326
2327CameraService::CameraState::~CameraState() {}
2328
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002329CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002330 Mutex::Autolock lock(mStatusLock);
2331 return mStatus;
2332}
2333
2334CameraParameters CameraService::CameraState::getShimParams() const {
2335 return mShimParams;
2336}
2337
2338void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2339 mShimParams = params;
2340}
2341
2342int CameraService::CameraState::getCost() const {
2343 return mCost;
2344}
2345
2346std::set<String8> CameraService::CameraState::getConflicting() const {
2347 return mConflicting;
2348}
2349
2350String8 CameraService::CameraState::getId() const {
2351 return mId;
2352}
2353
2354// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002355// ClientEventListener
2356// ----------------------------------------------------------------------------
2357
2358void CameraService::ClientEventListener::onClientAdded(
2359 const resource_policy::ClientDescriptor<String8,
2360 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002361 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002362 if (basicClient.get() != nullptr) {
2363 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2364 notifier.noteStartCamera(descriptor.getKey(),
2365 static_cast<int>(basicClient->getClientUid()));
2366 }
2367}
2368
2369void CameraService::ClientEventListener::onClientRemoved(
2370 const resource_policy::ClientDescriptor<String8,
2371 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002372 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002373 if (basicClient.get() != nullptr) {
2374 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2375 notifier.noteStopCamera(descriptor.getKey(),
2376 static_cast<int>(basicClient->getClientUid()));
2377 }
2378}
2379
2380
2381// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002382// CameraClientManager
2383// ----------------------------------------------------------------------------
2384
Ruben Brunk99e69712015-05-26 17:25:07 -07002385CameraService::CameraClientManager::CameraClientManager() {
2386 setListener(std::make_shared<ClientEventListener>());
2387}
2388
Ruben Brunkcc776712015-02-17 20:18:47 -08002389CameraService::CameraClientManager::~CameraClientManager() {}
2390
2391sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2392 const String8& id) const {
2393 auto descriptor = get(id);
2394 if (descriptor == nullptr) {
2395 return sp<BasicClient>{nullptr};
2396 }
2397 return descriptor->getValue();
2398}
2399
2400String8 CameraService::CameraClientManager::toString() const {
2401 auto all = getAll();
2402 String8 ret("[");
2403 bool hasAny = false;
2404 for (auto& i : all) {
2405 hasAny = true;
2406 String8 key = i->getKey();
2407 int32_t cost = i->getCost();
2408 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00002409 int32_t score = i->getPriority().getScore();
2410 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08002411 auto conflicting = i->getConflicting();
2412 auto clientSp = i->getValue();
2413 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002414 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002415 if (clientSp.get() != nullptr) {
2416 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002417 uid_t clientUid = clientSp->getClientUid();
2418 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002419 }
Emilian Peev8131a262017-02-01 12:33:43 +00002420 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
2421 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002422
Ruben Brunk6267b532015-04-30 17:44:07 -07002423 if (clientSp.get() != nullptr) {
2424 ret.appendFormat("User Id: %d, ", clientUserId);
2425 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002426 if (packageName.size() != 0) {
2427 ret.appendFormat("Client Package Name: %s", packageName.string());
2428 }
2429
2430 ret.append(", Conflicting Client Devices: {");
2431 for (auto& j : conflicting) {
2432 ret.appendFormat("%s, ", j.string());
2433 }
2434 ret.append("})");
2435 }
2436 if (hasAny) ret.append("\n");
2437 ret.append("]\n");
2438 return ret;
2439}
2440
2441CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2442 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00002443 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
2444 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002445
2446 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Emilian Peev8131a262017-02-01 12:33:43 +00002447 key, value, cost, conflictingKeys, score, ownerId, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002448}
2449
2450CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2451 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2452 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00002453 partial->getConflicting(), partial->getPriority().getScore(),
2454 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002455}
2456
2457// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458
2459static const int kDumpLockRetries = 50;
2460static const int kDumpLockSleep = 60000;
2461
2462static bool tryLock(Mutex& mutex)
2463{
2464 bool locked = false;
2465 for (int i = 0; i < kDumpLockRetries; ++i) {
2466 if (mutex.tryLock() == NO_ERROR) {
2467 locked = true;
2468 break;
2469 }
2470 usleep(kDumpLockSleep);
2471 }
2472 return locked;
2473}
2474
2475status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002476 ATRACE_CALL();
2477
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002479 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 getCallingPid(),
2481 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002482 return NO_ERROR;
2483 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002484 bool locked = tryLock(mServiceLock);
2485 // failed to lock - CameraService is probably deadlocked
2486 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002487 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002488 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002489
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002490 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002491 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07002492
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002493 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002494 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002495
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002496 if (locked) mServiceLock.unlock();
2497 return NO_ERROR;
2498 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002499 dprintf(fd, "\n== Service global info: ==\n\n");
2500 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
2501 dprintf(fd, "Number of normal camera devices: %d\n", mNumberOfNormalCameras);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002502 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002503 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
2504 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002505
2506 dumpEventLog(fd);
2507
2508 bool stateLocked = tryLock(mCameraStatesLock);
2509 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002510 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002511 }
2512
2513 for (auto& state : mCameraStates) {
2514 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002515
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002516 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002517
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002518 CameraParameters p = state.second->getShimParams();
2519 if (!p.isEmpty()) {
2520 dprintf(fd, " Camera1 API shim is using parameters:\n ");
2521 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002522 }
2523
2524 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08002525 if (clientDescriptor != nullptr) {
2526 dprintf(fd, " Device %s is open. Client instance dump:\n",
2527 cameraId.string());
2528 dprintf(fd, " Client priority score: %d state: %d\n",
2529 clientDescriptor->getPriority().getScore(),
2530 clientDescriptor->getPriority().getState());
2531 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
2532
2533 auto client = clientDescriptor->getValue();
2534 dprintf(fd, " Client package: %s\n",
2535 String8(client->getPackageName()).string());
2536
2537 client->dumpClient(fd, args);
2538 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002539 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002540 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002541 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002542
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002543 }
2544
2545 if (stateLocked) mCameraStatesLock.unlock();
2546
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002547 if (locked) mServiceLock.unlock();
2548
Emilian Peevf53f66e2017-04-11 14:29:43 +01002549 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002550
2551 dprintf(fd, "\n== Vendor tags: ==\n\n");
2552
2553 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2554 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00002555 sp<VendorTagDescriptorCache> cache =
2556 VendorTagDescriptorCache::getGlobalVendorTagCache();
2557 if (cache == NULL) {
2558 dprintf(fd, "No vendor tags.\n");
2559 } else {
2560 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
2561 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002562 } else {
2563 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
2564 }
2565
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002566 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002567 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002568 camera3::CameraTraces::dump(fd, args);
2569
2570 // Process dump arguments, if any
2571 int n = args.size();
2572 String16 verboseOption("-v");
2573 String16 unreachableOption("--unreachable");
2574 for (int i = 0; i < n; i++) {
2575 if (args[i] == verboseOption) {
2576 // change logging level
2577 if (i + 1 >= n) continue;
2578 String8 levelStr(args[i+1]);
2579 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002580 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002581 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002582 } else if (args[i] == unreachableOption) {
2583 // Dump memory analysis
2584 // TODO - should limit be an argument parameter?
2585 UnreachableMemoryInfo info;
2586 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
2587 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002588 dprintf(fd, "\n== Unable to dump unreachable memory. "
2589 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002590 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002591 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002592 std::string s = info.ToString(/*log_contents*/ true);
2593 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594 }
2595 }
2596 }
2597 return NO_ERROR;
2598}
2599
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002600void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002601 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002602
2603 Mutex::Autolock l(mLogLock);
2604 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002605 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002606 }
2607
2608 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002609 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002610 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002611 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002612 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002613 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002614}
2615
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002616void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002617 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002618 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2619 if (mTorchClientMap[i] == who) {
2620 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002621 String8 cameraId = mTorchClientMap.keyAt(i);
2622 status_t res = mFlashlight->setTorchMode(cameraId, false);
2623 if (res) {
2624 ALOGE("%s: torch client died but couldn't turn off torch: "
2625 "%s (%d)", __FUNCTION__, strerror(-res), res);
2626 return;
2627 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002628 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002629 break;
2630 }
2631 }
2632}
2633
Ruben Brunkcc776712015-02-17 20:18:47 -08002634/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002635
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002636 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002637 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2638 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002639 */
2640
Ruben Brunka8ca9152015-04-07 14:23:40 -07002641 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2642
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002643 // check torch client
2644 handleTorchClientBinderDied(who);
2645
2646 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002647 if(!evictClientIdByRemote(who)) {
2648 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002649 return;
2650 }
2651
Ruben Brunkcc776712015-02-17 20:18:47 -08002652 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2653 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002654}
2655
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002656void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002657 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002658}
2659
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002660void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
2661 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002662 // Do not lock mServiceLock here or can get into a deadlock from
2663 // connect() -> disconnect -> updateStatus
2664
2665 auto state = getCameraState(cameraId);
2666
2667 if (state == nullptr) {
2668 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2669 cameraId.string());
2670 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002671 }
2672
Ruben Brunkcc776712015-02-17 20:18:47 -08002673 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2674 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2675 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002676 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002677
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002678 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002679 // Update torch status if it has a flash unit.
2680 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002681 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002682 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2683 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002684 TorchModeStatus newTorchStatus =
2685 status == StatusInternal::PRESENT ?
2686 TorchModeStatus::AVAILABLE_OFF :
2687 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002688 if (torchStatus != newTorchStatus) {
2689 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2690 }
2691 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002692 }
2693
2694 Mutex::Autolock lock(mStatusListenerLock);
2695
2696 for (auto& listener : mListenerList) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002697 listener->onStatusChanged(mapToInterface(status), String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08002698 }
2699 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002700}
2701
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002702template<class Func>
2703void CameraService::CameraState::updateStatus(StatusInternal status,
2704 const String8& cameraId,
2705 std::initializer_list<StatusInternal> rejectSourceStates,
2706 Func onStatusUpdatedLocked) {
2707 Mutex::Autolock lock(mStatusLock);
2708 StatusInternal oldStatus = mStatus;
2709 mStatus = status;
2710
2711 if (oldStatus == status) {
2712 return;
2713 }
2714
2715 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
2716 cameraId.string(), oldStatus, status);
2717
2718 if (oldStatus == StatusInternal::NOT_PRESENT &&
2719 (status != StatusInternal::PRESENT &&
2720 status != StatusInternal::ENUMERATING)) {
2721
2722 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
2723 __FUNCTION__);
2724 mStatus = oldStatus;
2725 return;
2726 }
2727
2728 /**
2729 * Sometimes we want to conditionally do a transition.
2730 * For example if a client disconnects, we want to go to PRESENT
2731 * only if we weren't already in NOT_PRESENT or ENUMERATING.
2732 */
2733 for (auto& rejectStatus : rejectSourceStates) {
2734 if (oldStatus == rejectStatus) {
2735 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
2736 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
2737 mStatus = oldStatus;
2738 return;
2739 }
2740 }
2741
2742 onStatusUpdatedLocked(cameraId, status);
2743}
2744
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07002745void CameraService::updateProxyDeviceState(int newState,
2746 const String8& cameraId, int facing, const String16& clientName) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002747 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2748 if (proxyBinder == nullptr) return;
2749 String16 id(cameraId);
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07002750 proxyBinder->notifyCameraState(id, newState, facing, clientName);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002751}
2752
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002753status_t CameraService::getTorchStatusLocked(
2754 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002755 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002756 if (!status) {
2757 return BAD_VALUE;
2758 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002759 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2760 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002761 // invalid camera ID or the camera doesn't have a flash unit
2762 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002763 }
2764
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002765 *status = mTorchStatusMap.valueAt(index);
2766 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002767}
2768
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002769status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002770 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002771 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2772 if (index == NAME_NOT_FOUND) {
2773 return BAD_VALUE;
2774 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002775 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002776
2777 return OK;
2778}
2779
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780}; // namespace android