blob: c2b71a2372ff2e5eeda1d2ad2b1b58bb9c4b5146 [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;
76using hardware::ICameraServiceListener;
77using hardware::camera::common::V1_0::CameraDeviceStatus;
78using hardware::camera::common::V1_0::TorchModeStatus;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080079
Mathias Agopian65ab4712010-07-14 17:59:35 -070080// ----------------------------------------------------------------------------
81// Logging support -- this is for debugging only
82// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070083volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070084
Steve Blockb8a80522011-12-20 16:23:08 +000085#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
86#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
88static void setLogLevel(int level) {
89 android_atomic_write(level, &gLogLevel);
90}
91
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080092// Convenience methods for constructing binder::Status objects for error returns
93
94#define STATUS_ERROR(errorCode, errorString) \
95 binder::Status::fromServiceSpecificError(errorCode, \
96 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
97
98#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
99 binder::Status::fromServiceSpecificError(errorCode, \
100 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
101 __VA_ARGS__))
102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103// ----------------------------------------------------------------------------
104
Igor Murashkincba2c162013-03-20 15:56:31 -0700105extern "C" {
106static void camera_device_status_change(
107 const struct camera_module_callbacks* callbacks,
108 int camera_id,
109 int new_status) {
110 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -0800111 static_cast<const CameraService*>(callbacks));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800112 String8 id = String8::format("%d", camera_id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700113
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800114 CameraDeviceStatus newStatus{CameraDeviceStatus::NOT_PRESENT};
115 switch (new_status) {
116 case CAMERA_DEVICE_STATUS_NOT_PRESENT:
117 newStatus = CameraDeviceStatus::NOT_PRESENT;
118 break;
119 case CAMERA_DEVICE_STATUS_PRESENT:
120 newStatus = CameraDeviceStatus::PRESENT;
121 break;
122 case CAMERA_DEVICE_STATUS_ENUMERATING:
123 newStatus = CameraDeviceStatus::ENUMERATING;
124 break;
125 default:
126 ALOGW("Unknown device status change to %d", new_status);
127 break;
128 }
129 cs->onDeviceStatusChanged(id, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700130}
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800131
132static void torch_mode_status_change(
133 const struct camera_module_callbacks* callbacks,
134 const char* camera_id,
135 int new_status) {
136 if (!callbacks || !camera_id) {
137 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
138 callbacks, camera_id);
139 }
140 sp<CameraService> cs = const_cast<CameraService*>(
141 static_cast<const CameraService*>(callbacks));
142
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800143 TorchModeStatus status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800144 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800145 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800146 status = TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800147 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800148 case TORCH_MODE_STATUS_AVAILABLE_OFF:
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800149 status = TorchModeStatus::AVAILABLE_OFF;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800150 break;
151 case TORCH_MODE_STATUS_AVAILABLE_ON:
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800152 status = TorchModeStatus::AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800153 break;
154 default:
155 ALOGE("Unknown torch status %d", new_status);
156 return;
157 }
158
159 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800160 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800161 status);
162}
Igor Murashkincba2c162013-03-20 15:56:31 -0700163} // extern "C"
164
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165// ----------------------------------------------------------------------------
166
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800167CameraService::CameraService() :
168 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800169 mNumberOfCameras(0), mNumberOfNormalCameras(0),
Emilian Peevf53f66e2017-04-11 14:29:43 +0100170 mSoundRef(0), mInitialized(false) {
Steve Blockdf64d152012-01-04 20:05:49 +0000171 ALOGI("CameraService started (pid=%d)", getpid());
Igor Murashkinbfc99152013-02-27 12:55:20 -0800172
Igor Murashkincba2c162013-03-20 15:56:31 -0700173 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800174 this->torch_mode_status_change = android::torch_mode_status_change;
175
Ruben Brunkcc776712015-02-17 20:18:47 -0800176 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177}
178
Iliyan Malchev8951a972011-04-14 16:55:59 -0700179void CameraService::onFirstRef()
180{
Ruben Brunkcc776712015-02-17 20:18:47 -0800181 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800182
Iliyan Malchev8951a972011-04-14 16:55:59 -0700183 BnCameraService::onFirstRef();
184
Ruben Brunk99e69712015-05-26 17:25:07 -0700185 // Update battery life tracking if service is restarting
186 BatteryNotifier& notifier(BatteryNotifier::getInstance());
187 notifier.noteResetCamera();
188 notifier.noteResetFlashlight();
189
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800190 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800191
Emilian Peevf53f66e2017-04-11 14:29:43 +0100192 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800193 if (res == OK) {
194 mInitialized = true;
195 }
196
197 CameraService::pingCameraServiceProxy();
198}
199
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800200status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800201 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100202 Mutex::Autolock l(mServiceLock);
203
204 if (nullptr == mCameraProviderManager.get()) {
205 mCameraProviderManager = new CameraProviderManager();
206 res = mCameraProviderManager->initialize(this);
207 if (res != OK) {
208 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
209 __FUNCTION__, strerror(-res), res);
210 return res;
211 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800212 }
213
214 mNumberOfCameras = mCameraProviderManager->getCameraCount();
Emilian Peevf53f66e2017-04-11 14:29:43 +0100215 mNumberOfNormalCameras =
216 mCameraProviderManager->getAPI1CompatibleCameraCount();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800217
Yin-Chia Yeh067428c2017-01-13 15:19:24 -0800218 // Setup vendor tags before we call get_camera_info the first time
219 // because HAL might need to setup static vendor keys in get_camera_info
220 // TODO: maybe put this into CameraProviderManager::initialize()?
221 mCameraProviderManager->setUpVendorTags();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800222
Emilian Peevaee727d2017-05-04 16:35:48 +0100223 if (nullptr == mFlashlight.get()) {
224 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
225 }
226
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800227 res = mFlashlight->findFlashUnits();
228 if (res != OK) {
229 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
230 }
231
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800232 for (auto& cameraId : mCameraProviderManager->getCameraDeviceIds()) {
Emilian Peevaee727d2017-05-04 16:35:48 +0100233 String8 id8 = String8(cameraId.c_str());
234 {
235 Mutex::Autolock lock(mCameraStatesLock);
236 auto iter = mCameraStates.find(id8);
237 if (iter != mCameraStates.end()) {
238 continue;
239 }
240 }
241
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800242 hardware::camera::common::V1_0::CameraResourceCost cost;
243 res = mCameraProviderManager->getResourceCost(cameraId, &cost);
244 if (res != OK) {
245 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
246 continue;
247 }
248 std::set<String8> conflicting;
249 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
250 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
251 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800252
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700253 {
254 Mutex::Autolock lock(mCameraStatesLock);
255 mCameraStates.emplace(id8,
256 std::make_shared<CameraState>(id8, cost.resourceCost, conflicting));
257 }
258
259 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260
261 if (mFlashlight->hasFlashUnit(id8)) {
Emilian Peevaee727d2017-05-04 16:35:48 +0100262 mTorchStatusMap.add(id8, TorchModeStatus::AVAILABLE_OFF);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263 }
264 }
265
266 return OK;
267}
268
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700269sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800270 sp<ICameraServiceProxy> proxyBinder = nullptr;
271#ifndef __BRILLO__
Ruben Brunk2823ce02015-05-19 17:25:13 -0700272 sp<IServiceManager> sm = defaultServiceManager();
Eino-Ville Talvalaf4db13d2016-12-08 11:20:51 -0800273 // Use checkService because cameraserver normally starts before the
274 // system server and the proxy service. So the long timeout that getService
275 // has before giving up is inappropriate.
276 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800277 if (binder != nullptr) {
278 proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700279 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800280#endif
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700281 return proxyBinder;
282}
283
284void CameraService::pingCameraServiceProxy() {
285 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
286 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700287 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700288}
289
Mathias Agopian65ab4712010-07-14 17:59:35 -0700290CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800291 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700292}
293
Emilian Peevaee727d2017-05-04 16:35:48 +0100294void CameraService::onNewProviderRegistered() {
295 enumerateProviders();
296}
297
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800298void CameraService::onDeviceStatusChanged(const String8& id,
299 CameraDeviceStatus newHalStatus) {
300 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
301 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700302
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800303 StatusInternal newStatus = mapToInternal(newHalStatus);
304
Ruben Brunkcc776712015-02-17 20:18:47 -0800305 std::shared_ptr<CameraState> state = getCameraState(id);
306
307 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700308 if (newStatus == StatusInternal::PRESENT) {
309 ALOGW("%s: Unknown camera ID %s, probably newly registered?",
310 __FUNCTION__, id.string());
311 } else {
312 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
313 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700314 return;
315 }
316
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800317 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800318
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800319 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800320 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700321 return;
322 }
323
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800324 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700325 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
326 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800327 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700328 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800329 // Don't do this in updateStatus to avoid deadlock over mServiceLock
330 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700331
Ruben Brunkcc776712015-02-17 20:18:47 -0800332 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
333 // to this device until the status changes
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800334 updateStatus(StatusInternal::NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700335
Ruben Brunkcc776712015-02-17 20:18:47 -0800336 // Remove cached shim parameters
337 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700338
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700339 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800340 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700341 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800342
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700343 // Disconnect client
344 if (clientToDisconnect.get() != nullptr) {
345 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
346 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800347 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800348 clientToDisconnect->notifyError(
349 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800350 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800351 // Ensure not in binder RPC so client disconnect PID checks work correctly
352 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
353 "onDeviceStatusChanged must be called from the camera service process!");
354 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700355 }
356
Ruben Brunkcc776712015-02-17 20:18:47 -0800357 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800358 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700359 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
360 newStatus));
361 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800362 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700363 }
364
Igor Murashkincba2c162013-03-20 15:56:31 -0700365}
366
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800367void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800368 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800369 Mutex::Autolock al(mTorchStatusMutex);
370 onTorchStatusChangedLocked(cameraId, newStatus);
371}
372
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800373void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800374 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800375 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
376 __FUNCTION__, cameraId.string(), newStatus);
377
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800378 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800379 status_t res = getTorchStatusLocked(cameraId, &status);
380 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700381 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
382 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800383 return;
384 }
385 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800386 return;
387 }
388
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800389 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800390 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800391 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
392 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800393 return;
394 }
395
Ruben Brunkcc776712015-02-17 20:18:47 -0800396 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700397 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700398 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700399 auto iter = mTorchUidMap.find(cameraId);
400 if (iter != mTorchUidMap.end()) {
401 int oldUid = iter->second.second;
402 int newUid = iter->second.first;
403 BatteryNotifier& notifier(BatteryNotifier::getInstance());
404 if (oldUid != newUid) {
405 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800406 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700407 notifier.noteFlashlightOff(cameraId, oldUid);
408 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800409 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700410 notifier.noteFlashlightOn(cameraId, newUid);
411 }
412 iter->second.second = newUid;
413 } else {
414 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800415 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700416 notifier.noteFlashlightOn(cameraId, oldUid);
417 } else {
418 notifier.noteFlashlightOff(cameraId, oldUid);
419 }
420 }
421 }
422 }
423
424 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800425 Mutex::Autolock lock(mStatusListenerLock);
426 for (auto& i : mListenerList) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800427 i->onTorchStatusChanged(mapToInterface(newStatus), String16{cameraId});
Ruben Brunkcc776712015-02-17 20:18:47 -0800428 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800429 }
430}
431
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800432Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700433 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100434 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700435 switch (type) {
436 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800437 *numCameras = mNumberOfNormalCameras;
438 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700439 case CAMERA_TYPE_ALL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800440 *numCameras = mNumberOfCameras;
441 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700442 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800443 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700444 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800445 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
446 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700447 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800448 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449}
450
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800451Status CameraService::getCameraInfo(int cameraId,
452 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700453 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100454 Mutex::Autolock l(mServiceLock);
455
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800456 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800457 return STATUS_ERROR(ERROR_DISCONNECTED,
458 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700459 }
460
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800462 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
463 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 }
465
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800466 Status ret = Status::ok();
Emilian Peevf53f66e2017-04-11 14:29:43 +0100467 status_t err = mCameraProviderManager->getCameraInfo(std::to_string(cameraId), cameraInfo);
468 if (err != OK) {
469 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
470 "Error retrieving camera info from device %d: %s (%d)", cameraId,
471 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800472 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100473
Ruben Brunkcc776712015-02-17 20:18:47 -0800474 return ret;
475}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700476
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800477int CameraService::cameraIdToInt(const String8& cameraId) {
478 int id;
479 bool success = base::ParseInt(cameraId.string(), &id, 0);
480 if (!success) {
481 return -1;
482 }
483 return id;
484}
485
486Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800487 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700488 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700489 if (!cameraInfo) {
490 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800491 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700492 }
493
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800494 if (!mInitialized) {
495 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800496 return STATUS_ERROR(ERROR_DISCONNECTED,
497 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700498 }
499
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800500 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800501
Emilian Peevf53f66e2017-04-11 14:29:43 +0100502 status_t res = mCameraProviderManager->getCameraCharacteristics(
503 String8(cameraId).string(), cameraInfo);
504 if (res != OK) {
505 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
506 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
507 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700508 }
Zhijun He2b59be82013-09-25 10:14:30 -0700509
510 return ret;
511}
512
Ruben Brunkcc776712015-02-17 20:18:47 -0800513int CameraService::getCallingPid() {
514 return IPCThreadState::self()->getCallingPid();
515}
516
517int CameraService::getCallingUid() {
518 return IPCThreadState::self()->getCallingUid();
519}
520
521String8 CameraService::getFormattedCurrentTime() {
522 time_t now = time(nullptr);
523 char formattedTime[64];
524 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
525 return String8(formattedTime);
526}
527
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800528Status CameraService::getCameraVendorTagDescriptor(
529 /*out*/
530 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700531 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800532 if (!mInitialized) {
533 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800534 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800535 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800536 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
537 if (globalDescriptor != nullptr) {
538 *desc = *(globalDescriptor.get());
539 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800540 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800541}
542
Emilian Peev71c73a22017-03-21 16:35:51 +0000543Status CameraService::getCameraVendorTagCache(
544 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
545 ATRACE_CALL();
546 if (!mInitialized) {
547 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
548 return STATUS_ERROR(ERROR_DISCONNECTED,
549 "Camera subsystem not available");
550 }
551 sp<VendorTagDescriptorCache> globalCache =
552 VendorTagDescriptorCache::getGlobalVendorTagCache();
553 if (globalCache != nullptr) {
554 *cache = *(globalCache.get());
555 }
556 return Status::ok();
557}
558
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800559int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700560 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800561
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800562 int deviceVersion = 0;
563
Emilian Peevf53f66e2017-04-11 14:29:43 +0100564 status_t res;
565 hardware::hidl_version maxVersion{0,0};
566 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
567 &maxVersion);
568 if (res != OK) return -1;
569 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800570
Emilian Peevf53f66e2017-04-11 14:29:43 +0100571 hardware::CameraInfo info;
572 if (facing) {
573 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800574 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100575 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800576 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100577
Igor Murashkin634a5152013-02-20 17:15:11 -0800578 return deviceVersion;
579}
580
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800581Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700582 switch(err) {
583 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800585 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800586 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
587 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800588 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800589 return STATUS_ERROR(ERROR_DISCONNECTED,
590 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700591 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800592 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
593 "Camera HAL encountered error %d: %s",
594 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700595 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800596}
597
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800598Status CameraService::makeClient(const sp<CameraService>& cameraService,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800599 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800600 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
601 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
602 /*out*/sp<BasicClient>* client) {
603
Ruben Brunkcc776712015-02-17 20:18:47 -0800604 if (halVersion < 0 || halVersion == deviceVersion) {
605 // Default path: HAL version is unspecified by caller, create CameraClient
606 // based on device version reported by the HAL.
607 switch(deviceVersion) {
608 case CAMERA_DEVICE_API_VERSION_1_0:
609 if (effectiveApiLevel == API_1) { // Camera1 API route
610 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800611 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
612 facing, clientPid, clientUid, getpid(), legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800613 } else { // Camera2 API route
614 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800615 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800616 "Camera device \"%s\" HAL version %d does not support camera2 API",
617 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800618 }
619 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800620 case CAMERA_DEVICE_API_VERSION_3_0:
621 case CAMERA_DEVICE_API_VERSION_3_1:
622 case CAMERA_DEVICE_API_VERSION_3_2:
623 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700624 case CAMERA_DEVICE_API_VERSION_3_4:
Ruben Brunkcc776712015-02-17 20:18:47 -0800625 if (effectiveApiLevel == API_1) { // Camera1 API route
626 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800627 *client = new Camera2Client(cameraService, tmp, packageName, cameraIdToInt(cameraId),
628 facing, clientPid, clientUid, servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800629 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800630 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
631 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
632 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800633 facing, clientPid, clientUid, servicePid);
634 }
635 break;
636 default:
637 // Should not be reachable
638 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800639 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800640 "Camera device \"%s\" has unknown HAL version %d",
641 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800642 }
643 } else {
644 // A particular HAL version is requested by caller. Create CameraClient
645 // based on the requested HAL version.
646 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
647 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
648 // Only support higher HAL version device opened as HAL1.0 device.
649 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800650 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
651 facing, clientPid, clientUid, servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800652 } else {
653 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
654 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
655 " opened as HAL %x device", halVersion, deviceVersion,
656 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800657 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800658 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
659 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800660 }
661 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800662 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800663}
664
Ruben Brunk6267b532015-04-30 17:44:07 -0700665String8 CameraService::toString(std::set<userid_t> intSet) {
666 String8 s("");
667 bool first = true;
668 for (userid_t i : intSet) {
669 if (first) {
670 s.appendFormat("%d", i);
671 first = false;
672 } else {
673 s.appendFormat(", %d", i);
674 }
675 }
676 return s;
677}
678
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800679int32_t CameraService::mapToInterface(TorchModeStatus status) {
680 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
681 switch (status) {
682 case TorchModeStatus::NOT_AVAILABLE:
683 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
684 break;
685 case TorchModeStatus::AVAILABLE_OFF:
686 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
687 break;
688 case TorchModeStatus::AVAILABLE_ON:
689 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
690 break;
691 default:
692 ALOGW("Unknown new flash status: %d", status);
693 }
694 return serviceStatus;
695}
696
697CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
698 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
699 switch (status) {
700 case CameraDeviceStatus::NOT_PRESENT:
701 serviceStatus = StatusInternal::NOT_PRESENT;
702 break;
703 case CameraDeviceStatus::PRESENT:
704 serviceStatus = StatusInternal::PRESENT;
705 break;
706 case CameraDeviceStatus::ENUMERATING:
707 serviceStatus = StatusInternal::ENUMERATING;
708 break;
709 default:
710 ALOGW("Unknown new HAL device status: %d", status);
711 }
712 return serviceStatus;
713}
714
715int32_t CameraService::mapToInterface(StatusInternal status) {
716 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
717 switch (status) {
718 case StatusInternal::NOT_PRESENT:
719 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
720 break;
721 case StatusInternal::PRESENT:
722 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
723 break;
724 case StatusInternal::ENUMERATING:
725 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
726 break;
727 case StatusInternal::NOT_AVAILABLE:
728 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
729 break;
730 case StatusInternal::UNKNOWN:
731 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
732 break;
733 default:
734 ALOGW("Unknown new internal device status: %d", status);
735 }
736 return serviceStatus;
737}
738
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739Status CameraService::initializeShimMetadata(int cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800740 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700741
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800742 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800743 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800744 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800745 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800746 if (!(ret = connectHelper<ICameraClient,Client>(
747 sp<ICameraClient>{nullptr}, id, static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
748 internalPackageName, uid, USE_CALLING_PID,
749 API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
750 /*out*/ tmp)
751 ).isOk()) {
752 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700753 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800754 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700755}
756
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800757Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700758 /*out*/
759 CameraParameters* parameters) {
760
761 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
762
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800763 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700764
765 if (parameters == NULL) {
766 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800767 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700768 }
769
Ruben Brunkcc776712015-02-17 20:18:47 -0800770 String8 id = String8::format("%d", cameraId);
771
772 // Check if we already have parameters
773 {
774 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700775 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800776 auto cameraState = getCameraState(id);
777 if (cameraState == nullptr) {
778 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
780 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800781 }
782 CameraParameters p = cameraState->getShimParams();
783 if (!p.isEmpty()) {
784 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800785 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700786 }
787 }
788
Ruben Brunkcc776712015-02-17 20:18:47 -0800789 int64_t token = IPCThreadState::self()->clearCallingIdentity();
790 ret = initializeShimMetadata(cameraId);
791 IPCThreadState::self()->restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800792 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800793 // Error already logged by callee
794 return ret;
795 }
796
797 // Check for parameters again
798 {
799 // Scope for service lock
800 Mutex::Autolock lock(mServiceLock);
801 auto cameraState = getCameraState(id);
802 if (cameraState == nullptr) {
803 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800804 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
805 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700806 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800807 CameraParameters p = cameraState->getShimParams();
808 if (!p.isEmpty()) {
809 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800810 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700811 }
812 }
813
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
815 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800816 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700817}
818
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800819// Can camera service trust the caller based on the calling UID?
820static bool isTrustedCallingUid(uid_t uid) {
821 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700822 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800823 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700824 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800825 return true;
826 default:
827 return false;
828 }
829}
830
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700832 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
833 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500834
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700835#ifdef __BRILLO__
836 UNUSED(clientName8);
837 UNUSED(clientUid);
838 UNUSED(clientPid);
839 UNUSED(originalClientPid);
840#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700841 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
842 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800843 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -0800844 return allowed;
845 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700846#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -0800847
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800848 int callingPid = getCallingPid();
849
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800850 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800851 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
852 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800853 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
854 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700855 }
856
Ruben Brunkcc776712015-02-17 20:18:47 -0800857 if (getCameraState(cameraId) == nullptr) {
858 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
859 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800860 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
861 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862 }
863
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800864 status_t err = checkIfDeviceIsUsable(cameraId);
865 if (err != NO_ERROR) {
866 switch(err) {
867 case -ENODEV:
868 case -EBUSY:
869 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
870 "No camera device with ID \"%s\" currently available", cameraId.string());
871 default:
872 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
873 "Unknown error connecting to ID \"%s\"", cameraId.string());
874 }
875 }
876 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800877}
878
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800879Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700880 const String8& clientName8, int& clientUid, int& clientPid,
881 /*out*/int& originalClientPid) const {
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800882 int callingPid = getCallingPid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800883 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800885 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -0700886 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800887 clientUid = callingUid;
888 } else if (!isTrustedCallingUid(callingUid)) {
889 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
890 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800891 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
892 "Untrusted caller (calling PID %d, UID %d) trying to "
893 "forward camera access to camera %s for client %s (PID %d, UID %d)",
894 callingPid, callingUid, cameraId.string(),
895 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 }
897
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800898 // Check if we can trust clientPid
899 if (clientPid == USE_CALLING_PID) {
900 clientPid = callingPid;
901 } else if (!isTrustedCallingUid(callingUid)) {
902 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
903 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800904 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
905 "Untrusted caller (calling PID %d, UID %d) trying to "
906 "forward camera access to camera %s for client %s (PID %d, UID %d)",
907 callingPid, callingUid, cameraId.string(),
908 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800909 }
910
911 // If it's not calling from cameraserver, check the permission.
912 if (callingPid != getpid() &&
913 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
914 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800915 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
916 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
917 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800918 }
919
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700920 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
921 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700922 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700923 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924
Ruben Brunk6267b532015-04-30 17:44:07 -0700925 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800926
Ruben Brunka8ca9152015-04-07 14:23:40 -0700927 // Only allow clients who are being used by the current foreground device user, unless calling
928 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700929 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
930 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
931 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
932 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800933 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
934 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
935 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700936 }
937
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800938 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800939}
940
941status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
942 auto cameraState = getCameraState(cameraId);
943 int callingPid = getCallingPid();
944 if (cameraState == nullptr) {
945 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
946 cameraId.string());
947 return -ENODEV;
948 }
949
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800950 StatusInternal currentStatus = cameraState->getStatus();
951 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800952 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
953 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700954 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800955 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800956 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
957 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700958 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700959 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700960
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800962}
963
Ruben Brunkcc776712015-02-17 20:18:47 -0800964void CameraService::finishConnectLocked(const sp<BasicClient>& client,
965 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800966
Ruben Brunkcc776712015-02-17 20:18:47 -0800967 // Make a descriptor for the incoming client
968 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
969 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
970
971 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
972 String8(client->getPackageName()));
973
974 if (evicted.size() > 0) {
975 // This should never happen - clients should already have been removed in disconnect
976 for (auto& i : evicted) {
977 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
978 __FUNCTION__, i->getKey().string());
979 }
980
981 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
982 __FUNCTION__);
983 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700984
985 // And register a death notification for the client callback. Do
986 // this last to avoid Binder policy where a nested Binder
987 // transaction might be pre-empted to service the client death
988 // notification if the client process dies before linkToDeath is
989 // invoked.
990 sp<IBinder> remoteCallback = client->getRemote();
991 if (remoteCallback != nullptr) {
992 remoteCallback->linkToDeath(this);
993 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800994}
995
996status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
997 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
998 /*out*/
999 sp<BasicClient>* client,
1000 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001001 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001002 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001003 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001004 DescriptorPtr clientDescriptor;
1005 {
1006 if (effectiveApiLevel == API_1) {
1007 // If we are using API1, any existing client for this camera ID with the same remote
1008 // should be returned rather than evicted to allow MediaRecorder to work properly.
1009
1010 auto current = mActiveClientManager.get(cameraId);
1011 if (current != nullptr) {
1012 auto clientSp = current->getValue();
1013 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001014 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1015 ALOGW("CameraService connect called from same client, but with a different"
1016 " API level, evicting prior client...");
1017 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001018 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001019 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001020 *client = clientSp;
1021 return NO_ERROR;
1022 }
1023 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001024 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001025 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001026
Ruben Brunkcc776712015-02-17 20:18:47 -08001027 // Get current active client PIDs
1028 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1029 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001030
Emilian Peev8131a262017-02-01 12:33:43 +00001031 std::vector<int> priorityScores(ownerPids.size());
1032 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001033
Emilian Peev8131a262017-02-01 12:33:43 +00001034 // Get priority scores of all active PIDs
1035 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1036 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1037 /*out*/&priorityScores[0]);
1038 if (err != OK) {
1039 ALOGE("%s: Priority score query failed: %d",
1040 __FUNCTION__, err);
1041 return err;
1042 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001043
Ruben Brunkcc776712015-02-17 20:18:47 -08001044 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001045 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001046 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001047 pidToPriorityMap.emplace(ownerPids[i],
1048 resource_policy::ClientPriority(priorityScores[i], states[i]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001049 }
1050 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001051
Ruben Brunkcc776712015-02-17 20:18:47 -08001052 // Get state for the given cameraId
1053 auto state = getCameraState(cameraId);
1054 if (state == nullptr) {
1055 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1056 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001057 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001058 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001059 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001060
1061 // Make descriptor for incoming client
1062 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1063 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1064 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001065 priorityScores[priorityScores.size() - 1],
1066 clientPid,
1067 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001068
1069 // Find clients that would be evicted
1070 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1071
1072 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1073 // background, so we cannot do evictions
1074 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1075 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1076 " priority).", clientPid);
1077
1078 sp<BasicClient> clientSp = clientDescriptor->getValue();
1079 String8 curTime = getFormattedCurrentTime();
1080 auto incompatibleClients =
1081 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1082
1083 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001084 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001085 cameraId.string(), packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001086 priorityScores[priorityScores.size() - 1],
1087 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001088
1089 for (auto& i : incompatibleClients) {
1090 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001091 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1092 i->getKey().string(),
1093 String8{i->getValue()->getPackageName()}.string(),
1094 i->getOwnerId(), i->getPriority().getScore(),
1095 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001096 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001097 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001098 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001099 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001100 }
1101
1102 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001103 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001104 mEventLog.add(msg);
1105
1106 return -EBUSY;
1107 }
1108
1109 for (auto& i : evicted) {
1110 sp<BasicClient> clientSp = i->getValue();
1111 if (clientSp.get() == nullptr) {
1112 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1113
1114 // TODO: Remove this
1115 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1116 __FUNCTION__);
1117 mActiveClientManager.remove(i);
1118 continue;
1119 }
1120
1121 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1122 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001123 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001124
Ruben Brunkcc776712015-02-17 20:18:47 -08001125 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001126 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001127 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1128 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001129 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001130 i->getOwnerId(), i->getPriority().getScore(),
1131 i->getPriority().getState(), cameraId.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001133 priorityScores[priorityScores.size() - 1],
1134 states[states.size() - 1]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001135
1136 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001137 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001138 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001139 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001140 }
1141
Ruben Brunkcc776712015-02-17 20:18:47 -08001142 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1143 // other clients from connecting in mServiceLockWrapper if held
1144 mServiceLock.unlock();
1145
1146 // Clear caller identity temporarily so client disconnect PID checks work correctly
1147 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1148
1149 // Destroy evicted clients
1150 for (auto& i : evictedClients) {
1151 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001152 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001153 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001154
1155 IPCThreadState::self()->restoreCallingIdentity(token);
1156
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001157 for (const auto& i : evictedClients) {
1158 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1159 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1160 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1161 if (ret == TIMED_OUT) {
1162 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1163 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1164 mActiveClientManager.toString().string());
1165 return -EBUSY;
1166 }
1167 if (ret != NO_ERROR) {
1168 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1169 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1170 ret, mActiveClientManager.toString().string());
1171 return ret;
1172 }
1173 }
1174
1175 evictedClients.clear();
1176
Ruben Brunkcc776712015-02-17 20:18:47 -08001177 // Once clients have been disconnected, relock
1178 mServiceLock.lock();
1179
1180 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1181 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1182 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001183 }
1184
Ruben Brunkcc776712015-02-17 20:18:47 -08001185 *partial = clientDescriptor;
1186 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001187}
1188
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001189Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001190 const sp<ICameraClient>& cameraClient,
1191 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001192 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001193 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001194 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001195 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001196 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001197
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001198 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001199 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001200 String8 id = String8::format("%d", cameraId);
1201 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001202 ret = connectHelper<ICameraClient,Client>(cameraClient, id,
1203 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1204 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1205 /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001206
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001207 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001208 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001209 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001210 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 }
1212
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001213 *device = client;
1214 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215}
1216
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001217Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001218 const sp<ICameraClient>& cameraClient,
1219 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001220 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001221 int clientUid,
1222 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001224
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001225 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001226 String8 id = String8::format("%d", cameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001227
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001228 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001229 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001230 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion,
1231 clientPackageName, clientUid, USE_CALLING_PID, API_1,
1232 /*legacyMode*/ true, /*shimUpdateOnly*/ false,
1233 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001234
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001235 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001236 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001237 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001238 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001239 }
1240
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001241 *device = client;
1242 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001243}
1244
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001245Status CameraService::connectDevice(
1246 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001247 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001248 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 int clientUid,
1250 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001251 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001252
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001253 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001254 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001255 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001256 sp<CameraDeviceClient> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001257 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1258 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
1259 clientUid, USE_CALLING_PID, API_2,
1260 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1261 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001262
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001263 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001264 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001265 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001266 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001267 }
1268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001269 *device = client;
1270 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001271}
1272
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001273template<class CALLBACK, class CLIENT>
1274Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
1275 int halVersion, const String16& clientPackageName, int clientUid, int clientPid,
1276 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
1277 /*out*/sp<CLIENT>& device) {
1278 binder::Status ret = binder::Status::ok();
1279
1280 String8 clientName8(clientPackageName);
1281
1282 int originalClientPid = 0;
1283
1284 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1285 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1286 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1287 static_cast<int>(effectiveApiLevel));
1288
1289 sp<CLIENT> client = nullptr;
1290 {
1291 // Acquire mServiceLock and prevent other clients from connecting
1292 std::unique_ptr<AutoConditionLock> lock =
1293 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1294
1295 if (lock == nullptr) {
1296 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1297 , clientPid);
1298 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1299 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1300 cameraId.string(), clientName8.string(), clientPid);
1301 }
1302
1303 // Enforce client permissions and do basic sanity checks
1304 if(!(ret = validateConnectLocked(cameraId, clientName8,
1305 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1306 return ret;
1307 }
1308
1309 // Check the shim parameters after acquiring lock, if they have already been updated and
1310 // we were doing a shim update, return immediately
1311 if (shimUpdateOnly) {
1312 auto cameraState = getCameraState(cameraId);
1313 if (cameraState != nullptr) {
1314 if (!cameraState->getShimParams().isEmpty()) return ret;
1315 }
1316 }
1317
1318 status_t err;
1319
1320 sp<BasicClient> clientTmp = nullptr;
1321 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1322 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1323 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1324 /*out*/&partial)) != NO_ERROR) {
1325 switch (err) {
1326 case -ENODEV:
1327 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1328 "No camera device with ID \"%s\" currently available",
1329 cameraId.string());
1330 case -EBUSY:
1331 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1332 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1333 cameraId.string());
1334 default:
1335 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1336 "Unexpected error %s (%d) opening camera \"%s\"",
1337 strerror(-err), err, cameraId.string());
1338 }
1339 }
1340
1341 if (clientTmp.get() != nullptr) {
1342 // Handle special case for API1 MediaRecorder where the existing client is returned
1343 device = static_cast<CLIENT*>(clientTmp.get());
1344 return ret;
1345 }
1346
1347 // give flashlight a chance to close devices if necessary.
1348 mFlashlight->prepareDeviceOpen(cameraId);
1349
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001350 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001351 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001352 if (facing == -1) {
1353 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1354 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1355 "Unable to get camera device \"%s\" facing", cameraId.string());
1356 }
1357
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001358 sp<BasicClient> tmp = nullptr;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001359 if(!(ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001360 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
1361 /*out*/&tmp)).isOk()) {
1362 return ret;
1363 }
1364 client = static_cast<CLIENT*>(tmp.get());
1365
1366 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1367 __FUNCTION__);
1368
Emilian Peevf53f66e2017-04-11 14:29:43 +01001369 err = client->initialize(mCameraProviderManager);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001370 if (err != OK) {
1371 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001372 // Errors could be from the HAL module open call or from AppOpsManager
1373 switch(err) {
1374 case BAD_VALUE:
1375 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1376 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1377 case -EBUSY:
1378 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1379 "Camera \"%s\" is already open", cameraId.string());
1380 case -EUSERS:
1381 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1382 "Too many cameras already open, cannot open camera \"%s\"",
1383 cameraId.string());
1384 case PERMISSION_DENIED:
1385 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1386 "No permission to open camera \"%s\"", cameraId.string());
1387 case -EACCES:
1388 return STATUS_ERROR_FMT(ERROR_DISABLED,
1389 "Camera \"%s\" disabled by policy", cameraId.string());
1390 case -ENODEV:
1391 default:
1392 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1393 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1394 strerror(-err), err);
1395 }
1396 }
1397
1398 // Update shim paremeters for legacy clients
1399 if (effectiveApiLevel == API_1) {
1400 // Assume we have always received a Client subclass for API1
1401 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1402 String8 rawParams = shimClient->getParameters();
1403 CameraParameters params(rawParams);
1404
1405 auto cameraState = getCameraState(cameraId);
1406 if (cameraState != nullptr) {
1407 cameraState->setShimParams(params);
1408 } else {
1409 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1410 __FUNCTION__, cameraId.string());
1411 }
1412 }
1413
1414 if (shimUpdateOnly) {
1415 // If only updating legacy shim parameters, immediately disconnect client
1416 mServiceLock.unlock();
1417 client->disconnect();
1418 mServiceLock.lock();
1419 } else {
1420 // Otherwise, add client to active clients list
1421 finishConnectLocked(client, partial);
1422 }
1423 } // lock is destroyed, allow further connect calls
1424
1425 // Important: release the mutex here so the client can call back into the service from its
1426 // destructor (can be at the end of the call)
1427 device = client;
1428 return ret;
1429}
1430
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001431Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001432 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001433 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001434
1435 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001436 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001437 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001438 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1439 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001440 }
1441
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001442 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001443 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001444
1445 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 auto state = getCameraState(id);
1447 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001448 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1450 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001451 }
1452
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001453 StatusInternal cameraStatus = state->getStatus();
1454 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001455 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1456 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001457 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1458 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001459 }
1460
1461 {
1462 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001463 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464 status_t err = getTorchStatusLocked(id, &status);
1465 if (err != OK) {
1466 if (err == NAME_NOT_FOUND) {
1467 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1468 "Camera \"%s\" does not have a flash unit", id.string());
1469 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001470 ALOGE("%s: getting current torch status failed for camera %s",
1471 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001472 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1473 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1474 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001475 }
1476
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001477 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001478 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001479 ALOGE("%s: torch mode of camera %s is not available because "
1480 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001481 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1482 "Torch for camera \"%s\" is not available due to an existing camera user",
1483 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001484 } else {
1485 ALOGE("%s: torch mode of camera %s is not available due to "
1486 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001487 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1488 "Torch for camera \"%s\" is not available due to insufficient resources",
1489 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001490 }
1491 }
1492 }
1493
Ruben Brunk99e69712015-05-26 17:25:07 -07001494 {
1495 // Update UID map - this is used in the torch status changed callbacks, so must be done
1496 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001497 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001498 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1499 mTorchUidMap[id].first = uid;
1500 mTorchUidMap[id].second = uid;
1501 } else {
1502 // Set the pending UID
1503 mTorchUidMap[id].first = uid;
1504 }
1505 }
1506
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001507 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001508
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001509 if (err != OK) {
1510 int32_t errorCode;
1511 String8 msg;
1512 switch (err) {
1513 case -ENOSYS:
1514 msg = String8::format("Camera \"%s\" has no flashlight",
1515 id.string());
1516 errorCode = ERROR_ILLEGAL_ARGUMENT;
1517 break;
1518 default:
1519 msg = String8::format(
1520 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1521 id.string(), enabled, strerror(-err), err);
1522 errorCode = ERROR_INVALID_OPERATION;
1523 }
1524 ALOGE("%s: %s", __FUNCTION__, msg.string());
1525 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001526 }
1527
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001528 {
1529 // update the link to client's death
1530 Mutex::Autolock al(mTorchClientMapMutex);
1531 ssize_t index = mTorchClientMap.indexOfKey(id);
1532 if (enabled) {
1533 if (index == NAME_NOT_FOUND) {
1534 mTorchClientMap.add(id, clientBinder);
1535 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001536 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001537 mTorchClientMap.replaceValueAt(index, clientBinder);
1538 }
1539 clientBinder->linkToDeath(this);
1540 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001541 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001542 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001543 }
1544
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001545 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001546}
1547
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001548Status CameraService::notifySystemEvent(int32_t eventId,
1549 const std::vector<int32_t>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001550 ATRACE_CALL();
1551
Ruben Brunk36597b22015-03-20 22:15:57 -07001552 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001553 case ICameraService::EVENT_USER_SWITCHED: {
1554 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001555 break;
1556 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001558 default: {
1559 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1560 eventId);
1561 break;
1562 }
1563 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001564 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001565}
1566
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001567Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1568 /*out*/
1569 std::vector<hardware::CameraStatus> *cameraStatuses) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001570 ATRACE_CALL();
1571
Igor Murashkinbfc99152013-02-27 12:55:20 -08001572 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001573
Ruben Brunk3450ba72015-06-16 11:00:37 -07001574 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001575 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001576 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001577 }
1578
Igor Murashkinbfc99152013-02-27 12:55:20 -08001579 Mutex::Autolock lock(mServiceLock);
1580
Ruben Brunkcc776712015-02-17 20:18:47 -08001581 {
1582 Mutex::Autolock lock(mStatusListenerLock);
1583 for (auto& it : mListenerList) {
1584 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1585 ALOGW("%s: Tried to add listener %p which was already subscribed",
1586 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001588 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001589 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001590
1591 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001592 }
1593
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001594 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001595 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001596 Mutex::Autolock lock(mCameraStatesLock);
1597 for (auto& i : mCameraStates) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001598 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001599 }
1600 }
1601
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001602 /*
1603 * Immediately signal current torch status to this listener only
1604 * This may be a subset of all the devices, so don't include it in the response directly
1605 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001606 {
1607 Mutex::Autolock al(mTorchStatusMutex);
1608 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001609 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001610 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001611 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001612 }
1613
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001614 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001615}
Ruben Brunkcc776712015-02-17 20:18:47 -08001616
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001617Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001618 ATRACE_CALL();
1619
Igor Murashkinbfc99152013-02-27 12:55:20 -08001620 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1621
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001622 if (listener == 0) {
1623 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001624 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001625 }
1626
Igor Murashkinbfc99152013-02-27 12:55:20 -08001627 Mutex::Autolock lock(mServiceLock);
1628
Ruben Brunkcc776712015-02-17 20:18:47 -08001629 {
1630 Mutex::Autolock lock(mStatusListenerLock);
1631 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1632 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1633 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001634 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001635 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001636 }
1637 }
1638
1639 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1640 __FUNCTION__, listener.get());
1641
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001642 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001643}
1644
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001645Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001646
1647 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001648 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1649
1650 if (parameters == NULL) {
1651 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001652 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001653 }
1654
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001655 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001656
1657 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001658 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001659 // Error logged by caller
1660 return ret;
1661 }
1662
1663 String8 shimParamsString8 = shimParams.flatten();
1664 String16 shimParamsString16 = String16(shimParamsString8);
1665
1666 *parameters = shimParamsString16;
1667
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001668 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001669}
1670
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001671Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1672 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001673 ATRACE_CALL();
1674
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001675 const String8 id = String8(cameraId);
1676
1677 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001678
1679 switch (apiVersion) {
1680 case API_VERSION_1:
1681 case API_VERSION_2:
1682 break;
1683 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001684 String8 msg = String8::format("Unknown API version %d", apiVersion);
1685 ALOGE("%s: %s", __FUNCTION__, msg.string());
1686 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001687 }
1688
Emilian Peev28ad2ea2017-02-07 16:14:32 +00001689 int deviceVersion = getDeviceVersion(id);
Igor Murashkin65d14b92014-06-17 12:03:20 -07001690 switch(deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001691 case CAMERA_DEVICE_API_VERSION_1_0:
1692 case CAMERA_DEVICE_API_VERSION_3_0:
1693 case CAMERA_DEVICE_API_VERSION_3_1:
1694 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001695 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1696 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001697 *isSupported = false;
1698 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001699 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1700 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001701 *isSupported = true;
1702 }
1703 break;
1704 case CAMERA_DEVICE_API_VERSION_3_2:
1705 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001706 case CAMERA_DEVICE_API_VERSION_3_4:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001707 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1708 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001709 *isSupported = true;
1710 break;
1711 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001712 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001713 ALOGE("%s: %s", __FUNCTION__, msg.string());
1714 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001715 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001716 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001717 String8 msg = String8::format("Unknown device version %x for device %s",
1718 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001719 ALOGE("%s: %s", __FUNCTION__, msg.string());
1720 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1721 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07001722 }
1723
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001724 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001725}
1726
Ruben Brunkcc776712015-02-17 20:18:47 -08001727void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001728 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001729 for (auto& i : mActiveClientManager.getAll()) {
1730 auto clientSp = i->getValue();
1731 if (clientSp.get() == client) {
1732 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001733 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001734 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001735}
1736
Ruben Brunkcc776712015-02-17 20:18:47 -08001737bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1738 const int callingPid = getCallingPid();
1739 const int servicePid = getpid();
1740 bool ret = false;
1741 {
1742 // Acquire mServiceLock and prevent other clients from connecting
1743 std::unique_ptr<AutoConditionLock> lock =
1744 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001745
Igor Murashkin634a5152013-02-20 17:15:11 -08001746
Ruben Brunkcc776712015-02-17 20:18:47 -08001747 std::vector<sp<BasicClient>> evicted;
1748 for (auto& i : mActiveClientManager.getAll()) {
1749 auto clientSp = i->getValue();
1750 if (clientSp.get() == nullptr) {
1751 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1752 mActiveClientManager.remove(i);
1753 continue;
1754 }
1755 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1756 callingPid == clientSp->getClientPid())) {
1757 mActiveClientManager.remove(i);
1758 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001759
Ruben Brunkcc776712015-02-17 20:18:47 -08001760 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001761 clientSp->notifyError(
1762 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001763 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001764 }
1765 }
1766
Ruben Brunkcc776712015-02-17 20:18:47 -08001767 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1768 // other clients from connecting in mServiceLockWrapper if held
1769 mServiceLock.unlock();
1770
Ruben Brunk36597b22015-03-20 22:15:57 -07001771 // Do not clear caller identity, remote caller should be client proccess
1772
Ruben Brunkcc776712015-02-17 20:18:47 -08001773 for (auto& i : evicted) {
1774 if (i.get() != nullptr) {
1775 i->disconnect();
1776 ret = true;
1777 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001778 }
1779
Ruben Brunkcc776712015-02-17 20:18:47 -08001780 // Reacquire mServiceLock
1781 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001782
Ruben Brunkcc776712015-02-17 20:18:47 -08001783 } // lock is destroyed, allow further connect calls
1784
1785 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001786}
1787
Ruben Brunkcc776712015-02-17 20:18:47 -08001788std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1789 const String8& cameraId) const {
1790 std::shared_ptr<CameraState> state;
1791 {
1792 Mutex::Autolock lock(mCameraStatesLock);
1793 auto iter = mCameraStates.find(cameraId);
1794 if (iter != mCameraStates.end()) {
1795 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 }
1797 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001798 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799}
1800
Ruben Brunkcc776712015-02-17 20:18:47 -08001801sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1802 // Remove from active clients list
1803 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1804 if (clientDescriptorPtr == nullptr) {
1805 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1806 cameraId.string());
1807 return sp<BasicClient>{nullptr};
1808 }
1809
1810 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001811}
1812
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001814 // Acquire mServiceLock and prevent other clients from connecting
1815 std::unique_ptr<AutoConditionLock> lock =
1816 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1817
Ruben Brunk6267b532015-04-30 17:44:07 -07001818 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001819 for (size_t i = 0; i < newUserIds.size(); i++) {
1820 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001821 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001822 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07001823 return;
1824 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001825 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001826 }
1827
Ruben Brunka8ca9152015-04-07 14:23:40 -07001828
Ruben Brunk6267b532015-04-30 17:44:07 -07001829 if (newAllowedUsers == mAllowedUsers) {
1830 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1831 return;
1832 }
1833
1834 logUserSwitch(mAllowedUsers, newAllowedUsers);
1835
1836 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001837
1838 // Current user has switched, evict all current clients.
1839 std::vector<sp<BasicClient>> evicted;
1840 for (auto& i : mActiveClientManager.getAll()) {
1841 auto clientSp = i->getValue();
1842
1843 if (clientSp.get() == nullptr) {
1844 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1845 continue;
1846 }
1847
Ruben Brunk6267b532015-04-30 17:44:07 -07001848 // Don't evict clients that are still allowed.
1849 uid_t clientUid = clientSp->getClientUid();
1850 userid_t clientUserId = multiuser_get_user_id(clientUid);
1851 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1852 continue;
1853 }
1854
Ruben Brunk36597b22015-03-20 22:15:57 -07001855 evicted.push_back(clientSp);
1856
1857 String8 curTime = getFormattedCurrentTime();
1858
1859 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1860 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001861
Ruben Brunk36597b22015-03-20 22:15:57 -07001862 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001863 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001864 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
1865 " to user switch.", i->getKey().string(),
1866 String8{clientSp->getPackageName()}.string(),
1867 i->getOwnerId(), i->getPriority().getScore(),
1868 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001869
1870 }
1871
1872 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1873 // blocking other clients from connecting in mServiceLockWrapper if held.
1874 mServiceLock.unlock();
1875
1876 // Clear caller identity temporarily so client disconnect PID checks work correctly
1877 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1878
1879 for (auto& i : evicted) {
1880 i->disconnect();
1881 }
1882
1883 IPCThreadState::self()->restoreCallingIdentity(token);
1884
1885 // Reacquire mServiceLock
1886 mServiceLock.lock();
1887}
Ruben Brunkcc776712015-02-17 20:18:47 -08001888
Ruben Brunka8ca9152015-04-07 14:23:40 -07001889void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001890 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001891 Mutex::Autolock l(mLogLock);
1892 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893}
1894
Ruben Brunka8ca9152015-04-07 14:23:40 -07001895void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001896 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001897 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001898 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001899 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001900}
1901
1902void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001903 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001904 // Log the clients evicted
1905 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001906 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001907}
1908
1909void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001910 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001911 // Log the client rejected
1912 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001913 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001914}
1915
Ruben Brunk6267b532015-04-30 17:44:07 -07001916void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1917 const std::set<userid_t>& newUserIds) {
1918 String8 newUsers = toString(newUserIds);
1919 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001920 if (oldUsers.size() == 0) {
1921 oldUsers = "<None>";
1922 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07001923 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001924 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07001925 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001926}
1927
1928void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1929 // Log the device removal
1930 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1931}
1932
1933void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1934 // Log the device removal
1935 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1936}
1937
1938void CameraService::logClientDied(int clientPid, const char* reason) {
1939 // Log the device removal
1940 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001941}
1942
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001943void CameraService::logServiceError(const char* msg, int errorCode) {
1944 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001945 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001946}
1947
Ruben Brunk36597b22015-03-20 22:15:57 -07001948status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1949 uint32_t flags) {
1950
1951 const int pid = getCallingPid();
1952 const int selfPid = getpid();
1953
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 // Permission checks
1955 switch (code) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001956 case BnCameraService::NOTIFYSYSTEMEVENT: {
Ruben Brunk36597b22015-03-20 22:15:57 -07001957 if (pid != selfPid) {
1958 // Ensure we're being called by system_server, or similar process with
1959 // permissions to notify the camera service about system events
1960 if (!checkCallingPermission(
1961 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1962 const int uid = getCallingUid();
1963 ALOGE("Permission Denial: cannot send updates to camera service about system"
1964 " events from pid=%d, uid=%d", pid, uid);
1965 return PERMISSION_DENIED;
1966 }
1967 }
1968 break;
1969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 }
1971
1972 return BnCameraService::onTransact(code, data, reply, flags);
1973}
1974
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975// We share the media players for shutter and recording sound for all clients.
1976// A reference count is kept to determine when we will actually release the
1977// media players.
1978
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001979MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001981 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001982 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 mp->prepare();
1984 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001985 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986 return NULL;
1987 }
1988 return mp;
1989}
1990
1991void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001992 ATRACE_CALL();
1993
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 Mutex::Autolock lock(mSoundLock);
1995 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1996 if (mSoundRef++) return;
1997
1998 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001999 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
2000 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001}
2002
2003void CameraService::releaseSound() {
2004 Mutex::Autolock lock(mSoundLock);
2005 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
2006 if (--mSoundRef) return;
2007
2008 for (int i = 0; i < NUM_SOUNDS; i++) {
2009 if (mSoundPlayer[i] != 0) {
2010 mSoundPlayer[i]->disconnect();
2011 mSoundPlayer[i].clear();
2012 }
2013 }
2014}
2015
2016void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002017 ATRACE_CALL();
2018
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019 LOG1("playSound(%d)", kind);
2020 Mutex::Autolock lock(mSoundLock);
2021 sp<MediaPlayer> player = mSoundPlayer[kind];
2022 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002023 player->seekTo(0);
2024 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 }
2026}
2027
2028// ----------------------------------------------------------------------------
2029
2030CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002031 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002032 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002033 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002034 int clientPid, uid_t clientUid,
2035 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002036 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002037 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002038 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002039 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002040 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002041 servicePid),
2042 mCameraId(CameraService::cameraIdToInt(cameraIdStr))
Igor Murashkin634a5152013-02-20 17:15:11 -08002043{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002045 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002047 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002050
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002051 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052}
2053
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054// tear down the client
2055CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002056 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002057 mDestructionStarted = true;
2058
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002059 sCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002060 // unconditionally disconnect. function is idempotent
2061 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062}
2063
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002064sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2065
Igor Murashkin634a5152013-02-20 17:15:11 -08002066CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002067 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002068 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002069 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002070 int clientPid, uid_t clientUid,
2071 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002072 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2073 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2074 mServicePid(servicePid),
2075 mDisconnected(false),
2076 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002077{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002078 if (sCameraService == nullptr) {
2079 sCameraService = cameraService;
2080 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002081 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002082 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002083
2084 // In some cases the calling code has no access to the package it runs under.
2085 // For example, NDK camera API.
2086 // In this case we will get the packages for the calling UID and pick the first one
2087 // for attributing the app op. This will work correctly for runtime permissions
2088 // as for legacy apps we will toggle the app op for all packages in the UID.
2089 // The caveat is that the operation may be attributed to the wrong package and
2090 // stats based on app ops may be slightly off.
2091 if (mClientPackageName.size() <= 0) {
2092 sp<IServiceManager> sm = defaultServiceManager();
2093 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2094 if (binder == 0) {
2095 ALOGE("Cannot get permission service");
2096 // Leave mClientPackageName unchanged (empty) and the further interaction
2097 // with camera will fail in BasicClient::startCameraOps
2098 return;
2099 }
2100
2101 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2102 Vector<String16> packages;
2103
2104 permCtrl->getPackagesForUid(mClientUid, packages);
2105
2106 if (packages.isEmpty()) {
2107 ALOGE("No packages for calling UID");
2108 // Leave mClientPackageName unchanged (empty) and the further interaction
2109 // with camera will fail in BasicClient::startCameraOps
2110 return;
2111 }
2112 mClientPackageName = packages[0];
2113 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002114}
2115
2116CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002117 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002118 mDestructionStarted = true;
2119}
2120
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002121binder::Status CameraService::BasicClient::disconnect() {
2122 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002123 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002124 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002125 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002126 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002127
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002128 sCameraService->removeByClient(this);
2129 sCameraService->logDisconnected(mCameraIdStr, mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002130 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08002131
2132 sp<IBinder> remote = getRemote();
2133 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002134 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002135 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002136
2137 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002138 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002139 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2140 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2141 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002142
Igor Murashkincba2c162013-03-20 15:56:31 -07002143 // client shouldn't be able to call into us anymore
2144 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002145
2146 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002147}
2148
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002149status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2150 // No dumping of clients directly over Binder,
2151 // must go through CameraService::dump
2152 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2153 IPCThreadState::self()->getCallingUid(), NULL, 0);
2154 return OK;
2155}
2156
Ruben Brunkcc776712015-02-17 20:18:47 -08002157String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002158 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002159}
2160
2161
2162int CameraService::BasicClient::getClientPid() const {
2163 return mClientPid;
2164}
2165
Ruben Brunk6267b532015-04-30 17:44:07 -07002166uid_t CameraService::BasicClient::getClientUid() const {
2167 return mClientUid;
2168}
2169
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002170bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2171 // Defaults to API2.
2172 return level == API_2;
2173}
2174
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002175status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002176 ATRACE_CALL();
2177
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002178 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002179 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002180 mOpsCallback = new OpsCallback(this);
2181
Igor Murashkine6800ce2013-03-04 17:25:57 -08002182 {
2183 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002184 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002185 }
2186
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002187 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002188 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002189 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002190 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002191
Svetoslav28e8ef72015-05-11 19:21:31 -07002192 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002193 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2194 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002195 return PERMISSION_DENIED;
2196 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002197
Svetoslav28e8ef72015-05-11 19:21:31 -07002198 if (res == AppOpsManager::MODE_IGNORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002199 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2200 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002201 // Return the same error as for device policy manager rejection
2202 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002203 }
2204
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002205 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002206
2207 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002208 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002209
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002210 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002211 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2212 mCameraIdStr);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002213
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002214 return OK;
2215}
2216
2217status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002218 ATRACE_CALL();
2219
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002220 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002221 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002222 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002223 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002224 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002225 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002226
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002227 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
2228 StatusInternal::ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002229
Ruben Brunkcc776712015-02-17 20:18:47 -08002230 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002231 sCameraService->updateStatus(StatusInternal::PRESENT,
2232 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002233
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002234 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002235 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2236 mCameraIdStr);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002237 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002238 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002239 if (mOpsCallback != NULL) {
2240 mAppOpsManager.stopWatchingMode(mOpsCallback);
2241 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002242 mOpsCallback.clear();
2243
2244 return OK;
2245}
2246
2247void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002248 ATRACE_CALL();
2249
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002250 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002251 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002252
2253 if (op != AppOpsManager::OP_CAMERA) {
2254 ALOGW("Unexpected app ops notification received: %d", op);
2255 return;
2256 }
2257
2258 int32_t res;
2259 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002260 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002261 ALOGV("checkOp returns: %d, %s ", res,
2262 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2263 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2264 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2265 "UNKNOWN");
2266
2267 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002268 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002269 myName.string());
2270 // Reset the client PID to allow server-initiated disconnect,
2271 // and to prevent further calls by client.
2272 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002273 CaptureResultExtras resultExtras; // a dummy result (invalid)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002274 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002275 disconnect();
2276 }
2277}
2278
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279// ----------------------------------------------------------------------------
2280
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002281void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002282 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002283 (void) errorCode;
2284 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002285 if (mRemoteCallback != NULL) {
2286 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2287 } else {
2288 ALOGE("mRemoteCallback is NULL!!");
2289 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002290}
2291
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002292// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002293binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002294 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002295 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002296}
2297
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002298bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2299 return level == API_1;
2300}
2301
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002302CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2303 mClient(client) {
2304}
2305
2306void CameraService::Client::OpsCallback::opChanged(int32_t op,
2307 const String16& packageName) {
2308 sp<BasicClient> client = mClient.promote();
2309 if (client != NULL) {
2310 client->opChanged(op, packageName);
2311 }
2312}
2313
Mathias Agopian65ab4712010-07-14 17:59:35 -07002314// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002315// CameraState
2316// ----------------------------------------------------------------------------
2317
2318CameraService::CameraState::CameraState(const String8& id, int cost,
2319 const std::set<String8>& conflicting) : mId(id),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002320 mStatus(StatusInternal::PRESENT), mCost(cost), mConflicting(conflicting) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08002321
2322CameraService::CameraState::~CameraState() {}
2323
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002324CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002325 Mutex::Autolock lock(mStatusLock);
2326 return mStatus;
2327}
2328
2329CameraParameters CameraService::CameraState::getShimParams() const {
2330 return mShimParams;
2331}
2332
2333void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2334 mShimParams = params;
2335}
2336
2337int CameraService::CameraState::getCost() const {
2338 return mCost;
2339}
2340
2341std::set<String8> CameraService::CameraState::getConflicting() const {
2342 return mConflicting;
2343}
2344
2345String8 CameraService::CameraState::getId() const {
2346 return mId;
2347}
2348
2349// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002350// ClientEventListener
2351// ----------------------------------------------------------------------------
2352
2353void CameraService::ClientEventListener::onClientAdded(
2354 const resource_policy::ClientDescriptor<String8,
2355 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002356 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002357 if (basicClient.get() != nullptr) {
2358 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2359 notifier.noteStartCamera(descriptor.getKey(),
2360 static_cast<int>(basicClient->getClientUid()));
2361 }
2362}
2363
2364void CameraService::ClientEventListener::onClientRemoved(
2365 const resource_policy::ClientDescriptor<String8,
2366 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002367 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002368 if (basicClient.get() != nullptr) {
2369 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2370 notifier.noteStopCamera(descriptor.getKey(),
2371 static_cast<int>(basicClient->getClientUid()));
2372 }
2373}
2374
2375
2376// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002377// CameraClientManager
2378// ----------------------------------------------------------------------------
2379
Ruben Brunk99e69712015-05-26 17:25:07 -07002380CameraService::CameraClientManager::CameraClientManager() {
2381 setListener(std::make_shared<ClientEventListener>());
2382}
2383
Ruben Brunkcc776712015-02-17 20:18:47 -08002384CameraService::CameraClientManager::~CameraClientManager() {}
2385
2386sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2387 const String8& id) const {
2388 auto descriptor = get(id);
2389 if (descriptor == nullptr) {
2390 return sp<BasicClient>{nullptr};
2391 }
2392 return descriptor->getValue();
2393}
2394
2395String8 CameraService::CameraClientManager::toString() const {
2396 auto all = getAll();
2397 String8 ret("[");
2398 bool hasAny = false;
2399 for (auto& i : all) {
2400 hasAny = true;
2401 String8 key = i->getKey();
2402 int32_t cost = i->getCost();
2403 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00002404 int32_t score = i->getPriority().getScore();
2405 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08002406 auto conflicting = i->getConflicting();
2407 auto clientSp = i->getValue();
2408 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002409 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002410 if (clientSp.get() != nullptr) {
2411 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002412 uid_t clientUid = clientSp->getClientUid();
2413 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002414 }
Emilian Peev8131a262017-02-01 12:33:43 +00002415 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
2416 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002417
Ruben Brunk6267b532015-04-30 17:44:07 -07002418 if (clientSp.get() != nullptr) {
2419 ret.appendFormat("User Id: %d, ", clientUserId);
2420 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002421 if (packageName.size() != 0) {
2422 ret.appendFormat("Client Package Name: %s", packageName.string());
2423 }
2424
2425 ret.append(", Conflicting Client Devices: {");
2426 for (auto& j : conflicting) {
2427 ret.appendFormat("%s, ", j.string());
2428 }
2429 ret.append("})");
2430 }
2431 if (hasAny) ret.append("\n");
2432 ret.append("]\n");
2433 return ret;
2434}
2435
2436CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2437 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00002438 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
2439 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002440
2441 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Emilian Peev8131a262017-02-01 12:33:43 +00002442 key, value, cost, conflictingKeys, score, ownerId, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002443}
2444
2445CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2446 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2447 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00002448 partial->getConflicting(), partial->getPriority().getScore(),
2449 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002450}
2451
2452// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453
2454static const int kDumpLockRetries = 50;
2455static const int kDumpLockSleep = 60000;
2456
2457static bool tryLock(Mutex& mutex)
2458{
2459 bool locked = false;
2460 for (int i = 0; i < kDumpLockRetries; ++i) {
2461 if (mutex.tryLock() == NO_ERROR) {
2462 locked = true;
2463 break;
2464 }
2465 usleep(kDumpLockSleep);
2466 }
2467 return locked;
2468}
2469
2470status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002471 ATRACE_CALL();
2472
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002474 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475 getCallingPid(),
2476 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002477 return NO_ERROR;
2478 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002479 bool locked = tryLock(mServiceLock);
2480 // failed to lock - CameraService is probably deadlocked
2481 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002482 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002483 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002484
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002485 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002486 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07002487
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002488 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002489 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002490
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002491 if (locked) mServiceLock.unlock();
2492 return NO_ERROR;
2493 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002494 dprintf(fd, "\n== Service global info: ==\n\n");
2495 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
2496 dprintf(fd, "Number of normal camera devices: %d\n", mNumberOfNormalCameras);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002497 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002498 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
2499 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002500
2501 dumpEventLog(fd);
2502
2503 bool stateLocked = tryLock(mCameraStatesLock);
2504 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002505 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002506 }
2507
2508 for (auto& state : mCameraStates) {
2509 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002510
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002511 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002512
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002513 CameraParameters p = state.second->getShimParams();
2514 if (!p.isEmpty()) {
2515 dprintf(fd, " Camera1 API shim is using parameters:\n ");
2516 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002517 }
2518
2519 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08002520 if (clientDescriptor != nullptr) {
2521 dprintf(fd, " Device %s is open. Client instance dump:\n",
2522 cameraId.string());
2523 dprintf(fd, " Client priority score: %d state: %d\n",
2524 clientDescriptor->getPriority().getScore(),
2525 clientDescriptor->getPriority().getState());
2526 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
2527
2528 auto client = clientDescriptor->getValue();
2529 dprintf(fd, " Client package: %s\n",
2530 String8(client->getPackageName()).string());
2531
2532 client->dumpClient(fd, args);
2533 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002534 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002535 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002536 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002537
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002538 }
2539
2540 if (stateLocked) mCameraStatesLock.unlock();
2541
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002542 if (locked) mServiceLock.unlock();
2543
Emilian Peevf53f66e2017-04-11 14:29:43 +01002544 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002545
2546 dprintf(fd, "\n== Vendor tags: ==\n\n");
2547
2548 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2549 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00002550 sp<VendorTagDescriptorCache> cache =
2551 VendorTagDescriptorCache::getGlobalVendorTagCache();
2552 if (cache == NULL) {
2553 dprintf(fd, "No vendor tags.\n");
2554 } else {
2555 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
2556 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002557 } else {
2558 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
2559 }
2560
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002561 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002562 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002563 camera3::CameraTraces::dump(fd, args);
2564
2565 // Process dump arguments, if any
2566 int n = args.size();
2567 String16 verboseOption("-v");
2568 String16 unreachableOption("--unreachable");
2569 for (int i = 0; i < n; i++) {
2570 if (args[i] == verboseOption) {
2571 // change logging level
2572 if (i + 1 >= n) continue;
2573 String8 levelStr(args[i+1]);
2574 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002575 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002576 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002577 } else if (args[i] == unreachableOption) {
2578 // Dump memory analysis
2579 // TODO - should limit be an argument parameter?
2580 UnreachableMemoryInfo info;
2581 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
2582 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002583 dprintf(fd, "\n== Unable to dump unreachable memory. "
2584 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002585 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002586 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002587 std::string s = info.ToString(/*log_contents*/ true);
2588 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 }
2590 }
2591 }
2592 return NO_ERROR;
2593}
2594
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002595void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002596 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002597
2598 Mutex::Autolock l(mLogLock);
2599 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002600 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002601 }
2602
2603 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002604 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002605 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002606 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002607 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002608 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002609}
2610
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002611void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002612 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002613 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2614 if (mTorchClientMap[i] == who) {
2615 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002616 String8 cameraId = mTorchClientMap.keyAt(i);
2617 status_t res = mFlashlight->setTorchMode(cameraId, false);
2618 if (res) {
2619 ALOGE("%s: torch client died but couldn't turn off torch: "
2620 "%s (%d)", __FUNCTION__, strerror(-res), res);
2621 return;
2622 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002623 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002624 break;
2625 }
2626 }
2627}
2628
Ruben Brunkcc776712015-02-17 20:18:47 -08002629/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002630
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002631 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002632 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2633 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002634 */
2635
Ruben Brunka8ca9152015-04-07 14:23:40 -07002636 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2637
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002638 // check torch client
2639 handleTorchClientBinderDied(who);
2640
2641 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002642 if(!evictClientIdByRemote(who)) {
2643 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002644 return;
2645 }
2646
Ruben Brunkcc776712015-02-17 20:18:47 -08002647 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2648 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002649}
2650
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002651void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002652 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002653}
2654
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002655void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
2656 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002657 // Do not lock mServiceLock here or can get into a deadlock from
2658 // connect() -> disconnect -> updateStatus
2659
2660 auto state = getCameraState(cameraId);
2661
2662 if (state == nullptr) {
2663 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2664 cameraId.string());
2665 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002666 }
2667
Ruben Brunkcc776712015-02-17 20:18:47 -08002668 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2669 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2670 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002671 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002672
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002673 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002674 // Update torch status if it has a flash unit.
2675 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002676 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002677 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2678 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002679 TorchModeStatus newTorchStatus =
2680 status == StatusInternal::PRESENT ?
2681 TorchModeStatus::AVAILABLE_OFF :
2682 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002683 if (torchStatus != newTorchStatus) {
2684 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2685 }
2686 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002687 }
2688
2689 Mutex::Autolock lock(mStatusListenerLock);
2690
2691 for (auto& listener : mListenerList) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002692 listener->onStatusChanged(mapToInterface(status), String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08002693 }
2694 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002695}
2696
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002697template<class Func>
2698void CameraService::CameraState::updateStatus(StatusInternal status,
2699 const String8& cameraId,
2700 std::initializer_list<StatusInternal> rejectSourceStates,
2701 Func onStatusUpdatedLocked) {
2702 Mutex::Autolock lock(mStatusLock);
2703 StatusInternal oldStatus = mStatus;
2704 mStatus = status;
2705
2706 if (oldStatus == status) {
2707 return;
2708 }
2709
2710 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
2711 cameraId.string(), oldStatus, status);
2712
2713 if (oldStatus == StatusInternal::NOT_PRESENT &&
2714 (status != StatusInternal::PRESENT &&
2715 status != StatusInternal::ENUMERATING)) {
2716
2717 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
2718 __FUNCTION__);
2719 mStatus = oldStatus;
2720 return;
2721 }
2722
2723 /**
2724 * Sometimes we want to conditionally do a transition.
2725 * For example if a client disconnects, we want to go to PRESENT
2726 * only if we weren't already in NOT_PRESENT or ENUMERATING.
2727 */
2728 for (auto& rejectStatus : rejectSourceStates) {
2729 if (oldStatus == rejectStatus) {
2730 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
2731 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
2732 mStatus = oldStatus;
2733 return;
2734 }
2735 }
2736
2737 onStatusUpdatedLocked(cameraId, status);
2738}
2739
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002740void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2741 const String8& cameraId) {
2742 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2743 if (proxyBinder == nullptr) return;
2744 String16 id(cameraId);
2745 proxyBinder->notifyCameraState(id, newState);
2746}
2747
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002748status_t CameraService::getTorchStatusLocked(
2749 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002750 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002751 if (!status) {
2752 return BAD_VALUE;
2753 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002754 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2755 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002756 // invalid camera ID or the camera doesn't have a flash unit
2757 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002758 }
2759
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002760 *status = mTorchStatusMap.valueAt(index);
2761 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002762}
2763
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002764status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002765 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002766 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2767 if (index == NAME_NOT_FOUND) {
2768 return BAD_VALUE;
2769 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002770 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002771
2772 return OK;
2773}
2774
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775}; // namespace android