blob: 0031441ad05d206a4437a79f229a29a16f6df61e [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() {
201 mCameraProviderManager = new CameraProviderManager();
202 status_t res;
203 res = mCameraProviderManager->initialize(this);
204 if (res != OK) {
205 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
206 __FUNCTION__, strerror(-res), res);
207 return res;
208 }
209
210 mNumberOfCameras = mCameraProviderManager->getCameraCount();
Emilian Peevf53f66e2017-04-11 14:29:43 +0100211 mNumberOfNormalCameras =
212 mCameraProviderManager->getAPI1CompatibleCameraCount();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800213
Yin-Chia Yeh067428c2017-01-13 15:19:24 -0800214 // Setup vendor tags before we call get_camera_info the first time
215 // because HAL might need to setup static vendor keys in get_camera_info
216 // TODO: maybe put this into CameraProviderManager::initialize()?
217 mCameraProviderManager->setUpVendorTags();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800218
219 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
220 res = mFlashlight->findFlashUnits();
221 if (res != OK) {
222 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
223 }
224
225 // TODO: Verify device versions are in support
226
227 for (auto& cameraId : mCameraProviderManager->getCameraDeviceIds()) {
228 hardware::camera::common::V1_0::CameraResourceCost cost;
229 res = mCameraProviderManager->getResourceCost(cameraId, &cost);
230 if (res != OK) {
231 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
232 continue;
233 }
234 std::set<String8> conflicting;
235 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
236 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
237 }
238 String8 id8 = String8(cameraId.c_str());
239
240 Mutex::Autolock lock(mCameraStatesLock);
241 mCameraStates.emplace(id8,
242 std::make_shared<CameraState>(id8, cost.resourceCost, conflicting));
243
244 if (mFlashlight->hasFlashUnit(id8)) {
245 mTorchStatusMap.add(id8,
246 TorchModeStatus::AVAILABLE_OFF);
247 }
248 }
249
250 return OK;
251}
252
253
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700254sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800255 sp<ICameraServiceProxy> proxyBinder = nullptr;
256#ifndef __BRILLO__
Ruben Brunk2823ce02015-05-19 17:25:13 -0700257 sp<IServiceManager> sm = defaultServiceManager();
Eino-Ville Talvalaf4db13d2016-12-08 11:20:51 -0800258 // Use checkService because cameraserver normally starts before the
259 // system server and the proxy service. So the long timeout that getService
260 // has before giving up is inappropriate.
261 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800262 if (binder != nullptr) {
263 proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700264 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800265#endif
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700266 return proxyBinder;
267}
268
269void CameraService::pingCameraServiceProxy() {
270 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
271 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700272 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700273}
274
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800276 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277}
278
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800279void CameraService::onDeviceStatusChanged(const String8& id,
280 CameraDeviceStatus newHalStatus) {
281 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
282 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700283
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800284 StatusInternal newStatus = mapToInternal(newHalStatus);
285
Ruben Brunkcc776712015-02-17 20:18:47 -0800286 std::shared_ptr<CameraState> state = getCameraState(id);
287
288 if (state == nullptr) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800289 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700290 return;
291 }
292
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800293 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800294
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800295 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800296 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700297 return;
298 }
299
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800300 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700301 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
302 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800303 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700304 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800305 // Don't do this in updateStatus to avoid deadlock over mServiceLock
306 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700307
Ruben Brunkcc776712015-02-17 20:18:47 -0800308 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
309 // to this device until the status changes
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800310 updateStatus(StatusInternal::NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700311
Ruben Brunkcc776712015-02-17 20:18:47 -0800312 // Remove cached shim parameters
313 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700314
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700315 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800316 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700317 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800318
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700319 // Disconnect client
320 if (clientToDisconnect.get() != nullptr) {
321 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
322 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800323 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800324 clientToDisconnect->notifyError(
325 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800326 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800327 // Ensure not in binder RPC so client disconnect PID checks work correctly
328 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
329 "onDeviceStatusChanged must be called from the camera service process!");
330 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700331 }
332
Ruben Brunkcc776712015-02-17 20:18:47 -0800333 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800334 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700335 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
336 newStatus));
337 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800338 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700339 }
340
Igor Murashkincba2c162013-03-20 15:56:31 -0700341}
342
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800343void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800344 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800345 Mutex::Autolock al(mTorchStatusMutex);
346 onTorchStatusChangedLocked(cameraId, newStatus);
347}
348
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800349void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800350 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800351 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
352 __FUNCTION__, cameraId.string(), newStatus);
353
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800354 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800355 status_t res = getTorchStatusLocked(cameraId, &status);
356 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700357 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
358 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800359 return;
360 }
361 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800362 return;
363 }
364
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800365 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800366 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800367 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
368 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800369 return;
370 }
371
Ruben Brunkcc776712015-02-17 20:18:47 -0800372 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700373 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700374 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700375 auto iter = mTorchUidMap.find(cameraId);
376 if (iter != mTorchUidMap.end()) {
377 int oldUid = iter->second.second;
378 int newUid = iter->second.first;
379 BatteryNotifier& notifier(BatteryNotifier::getInstance());
380 if (oldUid != newUid) {
381 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800382 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700383 notifier.noteFlashlightOff(cameraId, oldUid);
384 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800385 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700386 notifier.noteFlashlightOn(cameraId, newUid);
387 }
388 iter->second.second = newUid;
389 } else {
390 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800391 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700392 notifier.noteFlashlightOn(cameraId, oldUid);
393 } else {
394 notifier.noteFlashlightOff(cameraId, oldUid);
395 }
396 }
397 }
398 }
399
400 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800401 Mutex::Autolock lock(mStatusListenerLock);
402 for (auto& i : mListenerList) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800403 i->onTorchStatusChanged(mapToInterface(newStatus), String16{cameraId});
Ruben Brunkcc776712015-02-17 20:18:47 -0800404 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800405 }
406}
407
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800408Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700409 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700410 switch (type) {
411 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800412 *numCameras = mNumberOfNormalCameras;
413 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700414 case CAMERA_TYPE_ALL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800415 *numCameras = mNumberOfCameras;
416 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700417 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800418 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700419 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800420 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
421 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700422 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800423 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424}
425
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800426Status CameraService::getCameraInfo(int cameraId,
427 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700428 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800429 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800430 return STATUS_ERROR(ERROR_DISCONNECTED,
431 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700432 }
433
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800435 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
436 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 }
438
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800439 Status ret = Status::ok();
Emilian Peevf53f66e2017-04-11 14:29:43 +0100440 status_t err = mCameraProviderManager->getCameraInfo(std::to_string(cameraId), cameraInfo);
441 if (err != OK) {
442 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
443 "Error retrieving camera info from device %d: %s (%d)", cameraId,
444 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800445 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100446
Ruben Brunkcc776712015-02-17 20:18:47 -0800447 return ret;
448}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700449
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800450int CameraService::cameraIdToInt(const String8& cameraId) {
451 int id;
452 bool success = base::ParseInt(cameraId.string(), &id, 0);
453 if (!success) {
454 return -1;
455 }
456 return id;
457}
458
459Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800460 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700461 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700462 if (!cameraInfo) {
463 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800464 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700465 }
466
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800467 if (!mInitialized) {
468 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800469 return STATUS_ERROR(ERROR_DISCONNECTED,
470 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700471 }
472
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800473 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800474
Emilian Peevf53f66e2017-04-11 14:29:43 +0100475 status_t res = mCameraProviderManager->getCameraCharacteristics(
476 String8(cameraId).string(), cameraInfo);
477 if (res != OK) {
478 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
479 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
480 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700481 }
Zhijun He2b59be82013-09-25 10:14:30 -0700482
483 return ret;
484}
485
Ruben Brunkcc776712015-02-17 20:18:47 -0800486int CameraService::getCallingPid() {
487 return IPCThreadState::self()->getCallingPid();
488}
489
490int CameraService::getCallingUid() {
491 return IPCThreadState::self()->getCallingUid();
492}
493
494String8 CameraService::getFormattedCurrentTime() {
495 time_t now = time(nullptr);
496 char formattedTime[64];
497 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
498 return String8(formattedTime);
499}
500
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800501Status CameraService::getCameraVendorTagDescriptor(
502 /*out*/
503 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700504 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800505 if (!mInitialized) {
506 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800507 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800508 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800509 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
510 if (globalDescriptor != nullptr) {
511 *desc = *(globalDescriptor.get());
512 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800513 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800514}
515
Emilian Peev71c73a22017-03-21 16:35:51 +0000516Status CameraService::getCameraVendorTagCache(
517 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
518 ATRACE_CALL();
519 if (!mInitialized) {
520 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
521 return STATUS_ERROR(ERROR_DISCONNECTED,
522 "Camera subsystem not available");
523 }
524 sp<VendorTagDescriptorCache> globalCache =
525 VendorTagDescriptorCache::getGlobalVendorTagCache();
526 if (globalCache != nullptr) {
527 *cache = *(globalCache.get());
528 }
529 return Status::ok();
530}
531
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800532int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700533 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800534
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800535 int deviceVersion = 0;
536
Emilian Peevf53f66e2017-04-11 14:29:43 +0100537 status_t res;
538 hardware::hidl_version maxVersion{0,0};
539 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
540 &maxVersion);
541 if (res != OK) return -1;
542 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800543
Emilian Peevf53f66e2017-04-11 14:29:43 +0100544 hardware::CameraInfo info;
545 if (facing) {
546 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800547 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100548 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800549 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100550
Igor Murashkin634a5152013-02-20 17:15:11 -0800551 return deviceVersion;
552}
553
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800554Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700555 switch(err) {
556 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800557 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800558 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800559 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
560 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800561 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800562 return STATUS_ERROR(ERROR_DISCONNECTED,
563 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700564 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800565 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
566 "Camera HAL encountered error %d: %s",
567 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700568 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800569}
570
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800571Status CameraService::makeClient(const sp<CameraService>& cameraService,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800572 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800573 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
574 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
575 /*out*/sp<BasicClient>* client) {
576
Ruben Brunkcc776712015-02-17 20:18:47 -0800577 if (halVersion < 0 || halVersion == deviceVersion) {
578 // Default path: HAL version is unspecified by caller, create CameraClient
579 // based on device version reported by the HAL.
580 switch(deviceVersion) {
581 case CAMERA_DEVICE_API_VERSION_1_0:
582 if (effectiveApiLevel == API_1) { // Camera1 API route
583 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800584 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
585 facing, clientPid, clientUid, getpid(), legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800586 } else { // Camera2 API route
587 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800588 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800589 "Camera device \"%s\" HAL version %d does not support camera2 API",
590 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800591 }
592 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800593 case CAMERA_DEVICE_API_VERSION_3_0:
594 case CAMERA_DEVICE_API_VERSION_3_1:
595 case CAMERA_DEVICE_API_VERSION_3_2:
596 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700597 case CAMERA_DEVICE_API_VERSION_3_4:
Ruben Brunkcc776712015-02-17 20:18:47 -0800598 if (effectiveApiLevel == API_1) { // Camera1 API route
599 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800600 *client = new Camera2Client(cameraService, tmp, packageName, cameraIdToInt(cameraId),
601 facing, clientPid, clientUid, servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800602 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800603 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
604 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
605 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800606 facing, clientPid, clientUid, servicePid);
607 }
608 break;
609 default:
610 // Should not be reachable
611 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800612 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800613 "Camera device \"%s\" has unknown HAL version %d",
614 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800615 }
616 } else {
617 // A particular HAL version is requested by caller. Create CameraClient
618 // based on the requested HAL version.
619 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
620 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
621 // Only support higher HAL version device opened as HAL1.0 device.
622 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800623 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
624 facing, clientPid, clientUid, servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800625 } else {
626 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
627 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
628 " opened as HAL %x device", halVersion, deviceVersion,
629 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800630 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800631 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
632 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800633 }
634 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800635 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800636}
637
Ruben Brunk6267b532015-04-30 17:44:07 -0700638String8 CameraService::toString(std::set<userid_t> intSet) {
639 String8 s("");
640 bool first = true;
641 for (userid_t i : intSet) {
642 if (first) {
643 s.appendFormat("%d", i);
644 first = false;
645 } else {
646 s.appendFormat(", %d", i);
647 }
648 }
649 return s;
650}
651
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800652int32_t CameraService::mapToInterface(TorchModeStatus status) {
653 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
654 switch (status) {
655 case TorchModeStatus::NOT_AVAILABLE:
656 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
657 break;
658 case TorchModeStatus::AVAILABLE_OFF:
659 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
660 break;
661 case TorchModeStatus::AVAILABLE_ON:
662 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
663 break;
664 default:
665 ALOGW("Unknown new flash status: %d", status);
666 }
667 return serviceStatus;
668}
669
670CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
671 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
672 switch (status) {
673 case CameraDeviceStatus::NOT_PRESENT:
674 serviceStatus = StatusInternal::NOT_PRESENT;
675 break;
676 case CameraDeviceStatus::PRESENT:
677 serviceStatus = StatusInternal::PRESENT;
678 break;
679 case CameraDeviceStatus::ENUMERATING:
680 serviceStatus = StatusInternal::ENUMERATING;
681 break;
682 default:
683 ALOGW("Unknown new HAL device status: %d", status);
684 }
685 return serviceStatus;
686}
687
688int32_t CameraService::mapToInterface(StatusInternal status) {
689 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
690 switch (status) {
691 case StatusInternal::NOT_PRESENT:
692 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
693 break;
694 case StatusInternal::PRESENT:
695 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
696 break;
697 case StatusInternal::ENUMERATING:
698 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
699 break;
700 case StatusInternal::NOT_AVAILABLE:
701 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
702 break;
703 case StatusInternal::UNKNOWN:
704 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
705 break;
706 default:
707 ALOGW("Unknown new internal device status: %d", status);
708 }
709 return serviceStatus;
710}
711
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800712Status CameraService::initializeShimMetadata(int cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800713 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700714
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800715 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800716 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800717 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800718 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800719 if (!(ret = connectHelper<ICameraClient,Client>(
720 sp<ICameraClient>{nullptr}, id, static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
721 internalPackageName, uid, USE_CALLING_PID,
722 API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
723 /*out*/ tmp)
724 ).isOk()) {
725 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700726 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800727 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700728}
729
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800730Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700731 /*out*/
732 CameraParameters* parameters) {
733
734 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
735
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800736 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700737
738 if (parameters == NULL) {
739 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800740 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700741 }
742
Ruben Brunkcc776712015-02-17 20:18:47 -0800743 String8 id = String8::format("%d", cameraId);
744
745 // Check if we already have parameters
746 {
747 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700748 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800749 auto cameraState = getCameraState(id);
750 if (cameraState == nullptr) {
751 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800752 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
753 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800754 }
755 CameraParameters p = cameraState->getShimParams();
756 if (!p.isEmpty()) {
757 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800758 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700759 }
760 }
761
Ruben Brunkcc776712015-02-17 20:18:47 -0800762 int64_t token = IPCThreadState::self()->clearCallingIdentity();
763 ret = initializeShimMetadata(cameraId);
764 IPCThreadState::self()->restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800765 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800766 // Error already logged by callee
767 return ret;
768 }
769
770 // Check for parameters again
771 {
772 // Scope for service lock
773 Mutex::Autolock lock(mServiceLock);
774 auto cameraState = getCameraState(id);
775 if (cameraState == nullptr) {
776 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800777 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
778 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700779 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800780 CameraParameters p = cameraState->getShimParams();
781 if (!p.isEmpty()) {
782 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700784 }
785 }
786
Ruben Brunkcc776712015-02-17 20:18:47 -0800787 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
788 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700790}
791
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800792// Can camera service trust the caller based on the calling UID?
793static bool isTrustedCallingUid(uid_t uid) {
794 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700795 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800796 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700797 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800798 return true;
799 default:
800 return false;
801 }
802}
803
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800804Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700805 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
806 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500807
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700808#ifdef __BRILLO__
809 UNUSED(clientName8);
810 UNUSED(clientUid);
811 UNUSED(clientPid);
812 UNUSED(originalClientPid);
813#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700814 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
815 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800816 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -0800817 return allowed;
818 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700819#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -0800820
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800821 int callingPid = getCallingPid();
822
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800823 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800824 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
825 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800826 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
827 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700828 }
829
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 if (getCameraState(cameraId) == nullptr) {
831 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
832 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800833 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
834 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 }
836
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800837 status_t err = checkIfDeviceIsUsable(cameraId);
838 if (err != NO_ERROR) {
839 switch(err) {
840 case -ENODEV:
841 case -EBUSY:
842 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
843 "No camera device with ID \"%s\" currently available", cameraId.string());
844 default:
845 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
846 "Unknown error connecting to ID \"%s\"", cameraId.string());
847 }
848 }
849 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800850}
851
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800852Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700853 const String8& clientName8, int& clientUid, int& clientPid,
854 /*out*/int& originalClientPid) const {
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800855 int callingPid = getCallingPid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800856 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800858 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800860 clientUid = callingUid;
861 } else if (!isTrustedCallingUid(callingUid)) {
862 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
863 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800864 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
865 "Untrusted caller (calling PID %d, UID %d) trying to "
866 "forward camera access to camera %s for client %s (PID %d, UID %d)",
867 callingPid, callingUid, cameraId.string(),
868 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869 }
870
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800871 // Check if we can trust clientPid
872 if (clientPid == USE_CALLING_PID) {
873 clientPid = callingPid;
874 } else if (!isTrustedCallingUid(callingUid)) {
875 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
876 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800877 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
878 "Untrusted caller (calling PID %d, UID %d) trying to "
879 "forward camera access to camera %s for client %s (PID %d, UID %d)",
880 callingPid, callingUid, cameraId.string(),
881 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800882 }
883
884 // If it's not calling from cameraserver, check the permission.
885 if (callingPid != getpid() &&
886 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
887 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800888 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
889 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
890 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800891 }
892
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700893 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
894 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700895 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700896 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897
Ruben Brunk6267b532015-04-30 17:44:07 -0700898 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800899
Ruben Brunka8ca9152015-04-07 14:23:40 -0700900 // Only allow clients who are being used by the current foreground device user, unless calling
901 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700902 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
903 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
904 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
905 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800906 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
907 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
908 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700909 }
910
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800911 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800912}
913
914status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
915 auto cameraState = getCameraState(cameraId);
916 int callingPid = getCallingPid();
917 if (cameraState == nullptr) {
918 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
919 cameraId.string());
920 return -ENODEV;
921 }
922
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800923 StatusInternal currentStatus = cameraState->getStatus();
924 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800925 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
926 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700927 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800928 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800929 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
930 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700931 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700932 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700933
Ruben Brunkcc776712015-02-17 20:18:47 -0800934 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800935}
936
Ruben Brunkcc776712015-02-17 20:18:47 -0800937void CameraService::finishConnectLocked(const sp<BasicClient>& client,
938 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800939
Ruben Brunkcc776712015-02-17 20:18:47 -0800940 // Make a descriptor for the incoming client
941 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
942 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
943
944 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
945 String8(client->getPackageName()));
946
947 if (evicted.size() > 0) {
948 // This should never happen - clients should already have been removed in disconnect
949 for (auto& i : evicted) {
950 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
951 __FUNCTION__, i->getKey().string());
952 }
953
954 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
955 __FUNCTION__);
956 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700957
958 // And register a death notification for the client callback. Do
959 // this last to avoid Binder policy where a nested Binder
960 // transaction might be pre-empted to service the client death
961 // notification if the client process dies before linkToDeath is
962 // invoked.
963 sp<IBinder> remoteCallback = client->getRemote();
964 if (remoteCallback != nullptr) {
965 remoteCallback->linkToDeath(this);
966 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800967}
968
969status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
970 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
971 /*out*/
972 sp<BasicClient>* client,
973 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700974 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800975 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700976 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800977 DescriptorPtr clientDescriptor;
978 {
979 if (effectiveApiLevel == API_1) {
980 // If we are using API1, any existing client for this camera ID with the same remote
981 // should be returned rather than evicted to allow MediaRecorder to work properly.
982
983 auto current = mActiveClientManager.get(cameraId);
984 if (current != nullptr) {
985 auto clientSp = current->getValue();
986 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700987 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
988 ALOGW("CameraService connect called from same client, but with a different"
989 " API level, evicting prior client...");
990 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700992 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800993 *client = clientSp;
994 return NO_ERROR;
995 }
996 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800997 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800998 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800999
Ruben Brunkcc776712015-02-17 20:18:47 -08001000 // Get current active client PIDs
1001 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1002 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001003
Emilian Peev8131a262017-02-01 12:33:43 +00001004 std::vector<int> priorityScores(ownerPids.size());
1005 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001006
Emilian Peev8131a262017-02-01 12:33:43 +00001007 // Get priority scores of all active PIDs
1008 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1009 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1010 /*out*/&priorityScores[0]);
1011 if (err != OK) {
1012 ALOGE("%s: Priority score query failed: %d",
1013 __FUNCTION__, err);
1014 return err;
1015 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001016
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001018 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001020 pidToPriorityMap.emplace(ownerPids[i],
1021 resource_policy::ClientPriority(priorityScores[i], states[i]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001022 }
1023 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001024
Ruben Brunkcc776712015-02-17 20:18:47 -08001025 // Get state for the given cameraId
1026 auto state = getCameraState(cameraId);
1027 if (state == nullptr) {
1028 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1029 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001030 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001031 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001032 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001033
1034 // Make descriptor for incoming client
1035 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1036 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1037 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001038 priorityScores[priorityScores.size() - 1],
1039 clientPid,
1040 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001041
1042 // Find clients that would be evicted
1043 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1044
1045 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1046 // background, so we cannot do evictions
1047 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1048 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1049 " priority).", clientPid);
1050
1051 sp<BasicClient> clientSp = clientDescriptor->getValue();
1052 String8 curTime = getFormattedCurrentTime();
1053 auto incompatibleClients =
1054 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1055
1056 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001057 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001058 cameraId.string(), packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001059 priorityScores[priorityScores.size() - 1],
1060 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001061
1062 for (auto& i : incompatibleClients) {
1063 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001064 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1065 i->getKey().string(),
1066 String8{i->getValue()->getPackageName()}.string(),
1067 i->getOwnerId(), i->getPriority().getScore(),
1068 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001069 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001070 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001071 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001072 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001073 }
1074
1075 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001076 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001077 mEventLog.add(msg);
1078
1079 return -EBUSY;
1080 }
1081
1082 for (auto& i : evicted) {
1083 sp<BasicClient> clientSp = i->getValue();
1084 if (clientSp.get() == nullptr) {
1085 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1086
1087 // TODO: Remove this
1088 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1089 __FUNCTION__);
1090 mActiveClientManager.remove(i);
1091 continue;
1092 }
1093
1094 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1095 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001096 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001097
Ruben Brunkcc776712015-02-17 20:18:47 -08001098 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001099 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001100 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1101 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001102 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001103 i->getOwnerId(), i->getPriority().getScore(),
1104 i->getPriority().getState(), cameraId.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001105 packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001106 priorityScores[priorityScores.size() - 1],
1107 states[states.size() - 1]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001108
1109 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001110 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001111 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001112 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001113 }
1114
Ruben Brunkcc776712015-02-17 20:18:47 -08001115 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1116 // other clients from connecting in mServiceLockWrapper if held
1117 mServiceLock.unlock();
1118
1119 // Clear caller identity temporarily so client disconnect PID checks work correctly
1120 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1121
1122 // Destroy evicted clients
1123 for (auto& i : evictedClients) {
1124 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001125 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001126 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001127
1128 IPCThreadState::self()->restoreCallingIdentity(token);
1129
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001130 for (const auto& i : evictedClients) {
1131 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1132 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1133 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1134 if (ret == TIMED_OUT) {
1135 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1136 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1137 mActiveClientManager.toString().string());
1138 return -EBUSY;
1139 }
1140 if (ret != NO_ERROR) {
1141 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1142 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1143 ret, mActiveClientManager.toString().string());
1144 return ret;
1145 }
1146 }
1147
1148 evictedClients.clear();
1149
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 // Once clients have been disconnected, relock
1151 mServiceLock.lock();
1152
1153 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1154 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1155 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001156 }
1157
Ruben Brunkcc776712015-02-17 20:18:47 -08001158 *partial = clientDescriptor;
1159 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001160}
1161
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001162Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001163 const sp<ICameraClient>& cameraClient,
1164 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001165 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001166 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001167 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001168 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001169 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001170
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001171 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001172 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001173 String8 id = String8::format("%d", cameraId);
1174 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 ret = connectHelper<ICameraClient,Client>(cameraClient, id,
1176 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1177 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1178 /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001179
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001180 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001181 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001182 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001183 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 }
1185
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001186 *device = client;
1187 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188}
1189
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001190Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001191 const sp<ICameraClient>& cameraClient,
1192 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001193 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001194 int clientUid,
1195 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001196 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001197
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001198 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001199 String8 id = String8::format("%d", cameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001200
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001201 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001202 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001203 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion,
1204 clientPackageName, clientUid, USE_CALLING_PID, API_1,
1205 /*legacyMode*/ true, /*shimUpdateOnly*/ false,
1206 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001207
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001208 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001209 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001210 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001212 }
1213
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001214 *device = client;
1215 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001216}
1217
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001218Status CameraService::connectDevice(
1219 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001220 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001221 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001222 int clientUid,
1223 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001224 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001225
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001226 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001227 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001228 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001229 sp<CameraDeviceClient> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001230 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1231 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
1232 clientUid, USE_CALLING_PID, API_2,
1233 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1234 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001235
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001236 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001237 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001238 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001239 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001240 }
1241
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 *device = client;
1243 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001244}
1245
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001246template<class CALLBACK, class CLIENT>
1247Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
1248 int halVersion, const String16& clientPackageName, int clientUid, int clientPid,
1249 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
1250 /*out*/sp<CLIENT>& device) {
1251 binder::Status ret = binder::Status::ok();
1252
1253 String8 clientName8(clientPackageName);
1254
1255 int originalClientPid = 0;
1256
1257 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1258 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1259 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1260 static_cast<int>(effectiveApiLevel));
1261
1262 sp<CLIENT> client = nullptr;
1263 {
1264 // Acquire mServiceLock and prevent other clients from connecting
1265 std::unique_ptr<AutoConditionLock> lock =
1266 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1267
1268 if (lock == nullptr) {
1269 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1270 , clientPid);
1271 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1272 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1273 cameraId.string(), clientName8.string(), clientPid);
1274 }
1275
1276 // Enforce client permissions and do basic sanity checks
1277 if(!(ret = validateConnectLocked(cameraId, clientName8,
1278 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1279 return ret;
1280 }
1281
1282 // Check the shim parameters after acquiring lock, if they have already been updated and
1283 // we were doing a shim update, return immediately
1284 if (shimUpdateOnly) {
1285 auto cameraState = getCameraState(cameraId);
1286 if (cameraState != nullptr) {
1287 if (!cameraState->getShimParams().isEmpty()) return ret;
1288 }
1289 }
1290
1291 status_t err;
1292
1293 sp<BasicClient> clientTmp = nullptr;
1294 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1295 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1296 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1297 /*out*/&partial)) != NO_ERROR) {
1298 switch (err) {
1299 case -ENODEV:
1300 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1301 "No camera device with ID \"%s\" currently available",
1302 cameraId.string());
1303 case -EBUSY:
1304 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1305 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1306 cameraId.string());
1307 default:
1308 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1309 "Unexpected error %s (%d) opening camera \"%s\"",
1310 strerror(-err), err, cameraId.string());
1311 }
1312 }
1313
1314 if (clientTmp.get() != nullptr) {
1315 // Handle special case for API1 MediaRecorder where the existing client is returned
1316 device = static_cast<CLIENT*>(clientTmp.get());
1317 return ret;
1318 }
1319
1320 // give flashlight a chance to close devices if necessary.
1321 mFlashlight->prepareDeviceOpen(cameraId);
1322
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001323 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001324 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001325 if (facing == -1) {
1326 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1327 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1328 "Unable to get camera device \"%s\" facing", cameraId.string());
1329 }
1330
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001331 sp<BasicClient> tmp = nullptr;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001332 if(!(ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001333 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
1334 /*out*/&tmp)).isOk()) {
1335 return ret;
1336 }
1337 client = static_cast<CLIENT*>(tmp.get());
1338
1339 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1340 __FUNCTION__);
1341
Emilian Peevf53f66e2017-04-11 14:29:43 +01001342 err = client->initialize(mCameraProviderManager);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001343 if (err != OK) {
1344 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001345 // Errors could be from the HAL module open call or from AppOpsManager
1346 switch(err) {
1347 case BAD_VALUE:
1348 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1349 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1350 case -EBUSY:
1351 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1352 "Camera \"%s\" is already open", cameraId.string());
1353 case -EUSERS:
1354 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1355 "Too many cameras already open, cannot open camera \"%s\"",
1356 cameraId.string());
1357 case PERMISSION_DENIED:
1358 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1359 "No permission to open camera \"%s\"", cameraId.string());
1360 case -EACCES:
1361 return STATUS_ERROR_FMT(ERROR_DISABLED,
1362 "Camera \"%s\" disabled by policy", cameraId.string());
1363 case -ENODEV:
1364 default:
1365 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1366 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1367 strerror(-err), err);
1368 }
1369 }
1370
1371 // Update shim paremeters for legacy clients
1372 if (effectiveApiLevel == API_1) {
1373 // Assume we have always received a Client subclass for API1
1374 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1375 String8 rawParams = shimClient->getParameters();
1376 CameraParameters params(rawParams);
1377
1378 auto cameraState = getCameraState(cameraId);
1379 if (cameraState != nullptr) {
1380 cameraState->setShimParams(params);
1381 } else {
1382 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1383 __FUNCTION__, cameraId.string());
1384 }
1385 }
1386
1387 if (shimUpdateOnly) {
1388 // If only updating legacy shim parameters, immediately disconnect client
1389 mServiceLock.unlock();
1390 client->disconnect();
1391 mServiceLock.lock();
1392 } else {
1393 // Otherwise, add client to active clients list
1394 finishConnectLocked(client, partial);
1395 }
1396 } // lock is destroyed, allow further connect calls
1397
1398 // Important: release the mutex here so the client can call back into the service from its
1399 // destructor (can be at the end of the call)
1400 device = client;
1401 return ret;
1402}
1403
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001404Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001405 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001406 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001407
1408 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001409 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001410 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001411 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1412 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001413 }
1414
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001415 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001416 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001417
1418 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001419 auto state = getCameraState(id);
1420 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001421 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001422 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1423 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001424 }
1425
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001426 StatusInternal cameraStatus = state->getStatus();
1427 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001428 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1429 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001430 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1431 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001432 }
1433
1434 {
1435 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001436 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001437 status_t err = getTorchStatusLocked(id, &status);
1438 if (err != OK) {
1439 if (err == NAME_NOT_FOUND) {
1440 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1441 "Camera \"%s\" does not have a flash unit", id.string());
1442 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001443 ALOGE("%s: getting current torch status failed for camera %s",
1444 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001445 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1446 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1447 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001448 }
1449
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001450 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001451 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001452 ALOGE("%s: torch mode of camera %s is not available because "
1453 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001454 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1455 "Torch for camera \"%s\" is not available due to an existing camera user",
1456 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001457 } else {
1458 ALOGE("%s: torch mode of camera %s is not available due to "
1459 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001460 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1461 "Torch for camera \"%s\" is not available due to insufficient resources",
1462 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001463 }
1464 }
1465 }
1466
Ruben Brunk99e69712015-05-26 17:25:07 -07001467 {
1468 // Update UID map - this is used in the torch status changed callbacks, so must be done
1469 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001470 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001471 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1472 mTorchUidMap[id].first = uid;
1473 mTorchUidMap[id].second = uid;
1474 } else {
1475 // Set the pending UID
1476 mTorchUidMap[id].first = uid;
1477 }
1478 }
1479
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001481
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001482 if (err != OK) {
1483 int32_t errorCode;
1484 String8 msg;
1485 switch (err) {
1486 case -ENOSYS:
1487 msg = String8::format("Camera \"%s\" has no flashlight",
1488 id.string());
1489 errorCode = ERROR_ILLEGAL_ARGUMENT;
1490 break;
1491 default:
1492 msg = String8::format(
1493 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1494 id.string(), enabled, strerror(-err), err);
1495 errorCode = ERROR_INVALID_OPERATION;
1496 }
1497 ALOGE("%s: %s", __FUNCTION__, msg.string());
1498 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001499 }
1500
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001501 {
1502 // update the link to client's death
1503 Mutex::Autolock al(mTorchClientMapMutex);
1504 ssize_t index = mTorchClientMap.indexOfKey(id);
1505 if (enabled) {
1506 if (index == NAME_NOT_FOUND) {
1507 mTorchClientMap.add(id, clientBinder);
1508 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001509 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001510 mTorchClientMap.replaceValueAt(index, clientBinder);
1511 }
1512 clientBinder->linkToDeath(this);
1513 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001514 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001515 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001516 }
1517
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001518 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001519}
1520
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001521Status CameraService::notifySystemEvent(int32_t eventId,
1522 const std::vector<int32_t>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001523 ATRACE_CALL();
1524
Ruben Brunk36597b22015-03-20 22:15:57 -07001525 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001526 case ICameraService::EVENT_USER_SWITCHED: {
1527 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001528 break;
1529 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001530 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001531 default: {
1532 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1533 eventId);
1534 break;
1535 }
1536 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001537 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001538}
1539
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001540Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1541 /*out*/
1542 std::vector<hardware::CameraStatus> *cameraStatuses) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001543 ATRACE_CALL();
1544
Igor Murashkinbfc99152013-02-27 12:55:20 -08001545 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001546
Ruben Brunk3450ba72015-06-16 11:00:37 -07001547 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001548 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001549 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001550 }
1551
Igor Murashkinbfc99152013-02-27 12:55:20 -08001552 Mutex::Autolock lock(mServiceLock);
1553
Ruben Brunkcc776712015-02-17 20:18:47 -08001554 {
1555 Mutex::Autolock lock(mStatusListenerLock);
1556 for (auto& it : mListenerList) {
1557 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1558 ALOGW("%s: Tried to add listener %p which was already subscribed",
1559 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001560 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001561 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001562 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001563
1564 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001565 }
1566
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001567 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001568 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001569 Mutex::Autolock lock(mCameraStatesLock);
1570 for (auto& i : mCameraStates) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001572 }
1573 }
1574
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001575 /*
1576 * Immediately signal current torch status to this listener only
1577 * This may be a subset of all the devices, so don't include it in the response directly
1578 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001579 {
1580 Mutex::Autolock al(mTorchStatusMutex);
1581 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001582 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001583 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001584 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001585 }
1586
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001588}
Ruben Brunkcc776712015-02-17 20:18:47 -08001589
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001590Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001591 ATRACE_CALL();
1592
Igor Murashkinbfc99152013-02-27 12:55:20 -08001593 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1594
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001595 if (listener == 0) {
1596 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001597 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001598 }
1599
Igor Murashkinbfc99152013-02-27 12:55:20 -08001600 Mutex::Autolock lock(mServiceLock);
1601
Ruben Brunkcc776712015-02-17 20:18:47 -08001602 {
1603 Mutex::Autolock lock(mStatusListenerLock);
1604 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1605 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1606 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001607 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001608 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001609 }
1610 }
1611
1612 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1613 __FUNCTION__, listener.get());
1614
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001615 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001616}
1617
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001618Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001619
1620 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001621 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1622
1623 if (parameters == NULL) {
1624 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001625 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001626 }
1627
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001629
1630 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001632 // Error logged by caller
1633 return ret;
1634 }
1635
1636 String8 shimParamsString8 = shimParams.flatten();
1637 String16 shimParamsString16 = String16(shimParamsString8);
1638
1639 *parameters = shimParamsString16;
1640
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001641 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001642}
1643
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001644Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1645 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001646 ATRACE_CALL();
1647
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001648 const String8 id = String8(cameraId);
1649
1650 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651
1652 switch (apiVersion) {
1653 case API_VERSION_1:
1654 case API_VERSION_2:
1655 break;
1656 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657 String8 msg = String8::format("Unknown API version %d", apiVersion);
1658 ALOGE("%s: %s", __FUNCTION__, msg.string());
1659 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001660 }
1661
Emilian Peev28ad2ea2017-02-07 16:14:32 +00001662 int deviceVersion = getDeviceVersion(id);
Igor Murashkin65d14b92014-06-17 12:03:20 -07001663 switch(deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001664 case CAMERA_DEVICE_API_VERSION_1_0:
1665 case CAMERA_DEVICE_API_VERSION_3_0:
1666 case CAMERA_DEVICE_API_VERSION_3_1:
1667 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001668 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1669 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001670 *isSupported = false;
1671 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001672 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1673 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001674 *isSupported = true;
1675 }
1676 break;
1677 case CAMERA_DEVICE_API_VERSION_3_2:
1678 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001679 case CAMERA_DEVICE_API_VERSION_3_4:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001680 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1681 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001682 *isSupported = true;
1683 break;
1684 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001685 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001686 ALOGE("%s: %s", __FUNCTION__, msg.string());
1687 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001688 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001689 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001690 String8 msg = String8::format("Unknown device version %x for device %s",
1691 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001692 ALOGE("%s: %s", __FUNCTION__, msg.string());
1693 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1694 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07001695 }
1696
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001697 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001698}
1699
Ruben Brunkcc776712015-02-17 20:18:47 -08001700void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001701 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001702 for (auto& i : mActiveClientManager.getAll()) {
1703 auto clientSp = i->getValue();
1704 if (clientSp.get() == client) {
1705 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001706 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001707 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001708}
1709
Ruben Brunkcc776712015-02-17 20:18:47 -08001710bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1711 const int callingPid = getCallingPid();
1712 const int servicePid = getpid();
1713 bool ret = false;
1714 {
1715 // Acquire mServiceLock and prevent other clients from connecting
1716 std::unique_ptr<AutoConditionLock> lock =
1717 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001718
Igor Murashkin634a5152013-02-20 17:15:11 -08001719
Ruben Brunkcc776712015-02-17 20:18:47 -08001720 std::vector<sp<BasicClient>> evicted;
1721 for (auto& i : mActiveClientManager.getAll()) {
1722 auto clientSp = i->getValue();
1723 if (clientSp.get() == nullptr) {
1724 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1725 mActiveClientManager.remove(i);
1726 continue;
1727 }
1728 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1729 callingPid == clientSp->getClientPid())) {
1730 mActiveClientManager.remove(i);
1731 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001732
Ruben Brunkcc776712015-02-17 20:18:47 -08001733 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001734 clientSp->notifyError(
1735 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001736 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001737 }
1738 }
1739
Ruben Brunkcc776712015-02-17 20:18:47 -08001740 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1741 // other clients from connecting in mServiceLockWrapper if held
1742 mServiceLock.unlock();
1743
Ruben Brunk36597b22015-03-20 22:15:57 -07001744 // Do not clear caller identity, remote caller should be client proccess
1745
Ruben Brunkcc776712015-02-17 20:18:47 -08001746 for (auto& i : evicted) {
1747 if (i.get() != nullptr) {
1748 i->disconnect();
1749 ret = true;
1750 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001751 }
1752
Ruben Brunkcc776712015-02-17 20:18:47 -08001753 // Reacquire mServiceLock
1754 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001755
Ruben Brunkcc776712015-02-17 20:18:47 -08001756 } // lock is destroyed, allow further connect calls
1757
1758 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001759}
1760
Ruben Brunkcc776712015-02-17 20:18:47 -08001761std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1762 const String8& cameraId) const {
1763 std::shared_ptr<CameraState> state;
1764 {
1765 Mutex::Autolock lock(mCameraStatesLock);
1766 auto iter = mCameraStates.find(cameraId);
1767 if (iter != mCameraStates.end()) {
1768 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 }
1770 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001771 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772}
1773
Ruben Brunkcc776712015-02-17 20:18:47 -08001774sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1775 // Remove from active clients list
1776 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1777 if (clientDescriptorPtr == nullptr) {
1778 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1779 cameraId.string());
1780 return sp<BasicClient>{nullptr};
1781 }
1782
1783 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001784}
1785
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001786void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001787 // Acquire mServiceLock and prevent other clients from connecting
1788 std::unique_ptr<AutoConditionLock> lock =
1789 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1790
Ruben Brunk6267b532015-04-30 17:44:07 -07001791 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 for (size_t i = 0; i < newUserIds.size(); i++) {
1793 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001794 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001795 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07001796 return;
1797 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001798 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001799 }
1800
Ruben Brunka8ca9152015-04-07 14:23:40 -07001801
Ruben Brunk6267b532015-04-30 17:44:07 -07001802 if (newAllowedUsers == mAllowedUsers) {
1803 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1804 return;
1805 }
1806
1807 logUserSwitch(mAllowedUsers, newAllowedUsers);
1808
1809 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001810
1811 // Current user has switched, evict all current clients.
1812 std::vector<sp<BasicClient>> evicted;
1813 for (auto& i : mActiveClientManager.getAll()) {
1814 auto clientSp = i->getValue();
1815
1816 if (clientSp.get() == nullptr) {
1817 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1818 continue;
1819 }
1820
Ruben Brunk6267b532015-04-30 17:44:07 -07001821 // Don't evict clients that are still allowed.
1822 uid_t clientUid = clientSp->getClientUid();
1823 userid_t clientUserId = multiuser_get_user_id(clientUid);
1824 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1825 continue;
1826 }
1827
Ruben Brunk36597b22015-03-20 22:15:57 -07001828 evicted.push_back(clientSp);
1829
1830 String8 curTime = getFormattedCurrentTime();
1831
1832 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1833 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001834
Ruben Brunk36597b22015-03-20 22:15:57 -07001835 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001836 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001837 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
1838 " to user switch.", i->getKey().string(),
1839 String8{clientSp->getPackageName()}.string(),
1840 i->getOwnerId(), i->getPriority().getScore(),
1841 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001842
1843 }
1844
1845 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1846 // blocking other clients from connecting in mServiceLockWrapper if held.
1847 mServiceLock.unlock();
1848
1849 // Clear caller identity temporarily so client disconnect PID checks work correctly
1850 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1851
1852 for (auto& i : evicted) {
1853 i->disconnect();
1854 }
1855
1856 IPCThreadState::self()->restoreCallingIdentity(token);
1857
1858 // Reacquire mServiceLock
1859 mServiceLock.lock();
1860}
Ruben Brunkcc776712015-02-17 20:18:47 -08001861
Ruben Brunka8ca9152015-04-07 14:23:40 -07001862void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001863 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001864 Mutex::Autolock l(mLogLock);
1865 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866}
1867
Ruben Brunka8ca9152015-04-07 14:23:40 -07001868void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001869 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001870 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001871 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001872 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001873}
1874
1875void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001876 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001877 // Log the clients evicted
1878 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001879 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001880}
1881
1882void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001883 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001884 // Log the client rejected
1885 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001886 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001887}
1888
Ruben Brunk6267b532015-04-30 17:44:07 -07001889void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1890 const std::set<userid_t>& newUserIds) {
1891 String8 newUsers = toString(newUserIds);
1892 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001893 if (oldUsers.size() == 0) {
1894 oldUsers = "<None>";
1895 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07001896 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001897 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07001898 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001899}
1900
1901void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1902 // Log the device removal
1903 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1904}
1905
1906void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1907 // Log the device removal
1908 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1909}
1910
1911void CameraService::logClientDied(int clientPid, const char* reason) {
1912 // Log the device removal
1913 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001914}
1915
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001916void CameraService::logServiceError(const char* msg, int errorCode) {
1917 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001918 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001919}
1920
Ruben Brunk36597b22015-03-20 22:15:57 -07001921status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1922 uint32_t flags) {
1923
1924 const int pid = getCallingPid();
1925 const int selfPid = getpid();
1926
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 // Permission checks
1928 switch (code) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001929 case BnCameraService::NOTIFYSYSTEMEVENT: {
Ruben Brunk36597b22015-03-20 22:15:57 -07001930 if (pid != selfPid) {
1931 // Ensure we're being called by system_server, or similar process with
1932 // permissions to notify the camera service about system events
1933 if (!checkCallingPermission(
1934 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1935 const int uid = getCallingUid();
1936 ALOGE("Permission Denial: cannot send updates to camera service about system"
1937 " events from pid=%d, uid=%d", pid, uid);
1938 return PERMISSION_DENIED;
1939 }
1940 }
1941 break;
1942 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 }
1944
1945 return BnCameraService::onTransact(code, data, reply, flags);
1946}
1947
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948// We share the media players for shutter and recording sound for all clients.
1949// A reference count is kept to determine when we will actually release the
1950// media players.
1951
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001952MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001954 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001955 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956 mp->prepare();
1957 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001958 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 return NULL;
1960 }
1961 return mp;
1962}
1963
1964void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001965 ATRACE_CALL();
1966
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 Mutex::Autolock lock(mSoundLock);
1968 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1969 if (mSoundRef++) return;
1970
1971 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001972 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1973 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974}
1975
1976void CameraService::releaseSound() {
1977 Mutex::Autolock lock(mSoundLock);
1978 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1979 if (--mSoundRef) return;
1980
1981 for (int i = 0; i < NUM_SOUNDS; i++) {
1982 if (mSoundPlayer[i] != 0) {
1983 mSoundPlayer[i]->disconnect();
1984 mSoundPlayer[i].clear();
1985 }
1986 }
1987}
1988
1989void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001990 ATRACE_CALL();
1991
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 LOG1("playSound(%d)", kind);
1993 Mutex::Autolock lock(mSoundLock);
1994 sp<MediaPlayer> player = mSoundPlayer[kind];
1995 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001996 player->seekTo(0);
1997 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 }
1999}
2000
2001// ----------------------------------------------------------------------------
2002
2003CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002004 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002005 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002006 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002007 int clientPid, uid_t clientUid,
2008 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002009 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002010 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002011 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002012 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002013 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002014 servicePid),
2015 mCameraId(CameraService::cameraIdToInt(cameraIdStr))
Igor Murashkin634a5152013-02-20 17:15:11 -08002016{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002018 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002020 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002023
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002024 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025}
2026
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027// tear down the client
2028CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002029 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002030 mDestructionStarted = true;
2031
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002032 sCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002033 // unconditionally disconnect. function is idempotent
2034 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035}
2036
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002037sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2038
Igor Murashkin634a5152013-02-20 17:15:11 -08002039CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002040 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002041 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002042 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002043 int clientPid, uid_t clientUid,
2044 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002045 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2046 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2047 mServicePid(servicePid),
2048 mDisconnected(false),
2049 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002050{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002051 if (sCameraService == nullptr) {
2052 sCameraService = cameraService;
2053 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002054 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002055 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002056
2057 // In some cases the calling code has no access to the package it runs under.
2058 // For example, NDK camera API.
2059 // In this case we will get the packages for the calling UID and pick the first one
2060 // for attributing the app op. This will work correctly for runtime permissions
2061 // as for legacy apps we will toggle the app op for all packages in the UID.
2062 // The caveat is that the operation may be attributed to the wrong package and
2063 // stats based on app ops may be slightly off.
2064 if (mClientPackageName.size() <= 0) {
2065 sp<IServiceManager> sm = defaultServiceManager();
2066 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2067 if (binder == 0) {
2068 ALOGE("Cannot get permission service");
2069 // Leave mClientPackageName unchanged (empty) and the further interaction
2070 // with camera will fail in BasicClient::startCameraOps
2071 return;
2072 }
2073
2074 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2075 Vector<String16> packages;
2076
2077 permCtrl->getPackagesForUid(mClientUid, packages);
2078
2079 if (packages.isEmpty()) {
2080 ALOGE("No packages for calling UID");
2081 // Leave mClientPackageName unchanged (empty) and the further interaction
2082 // with camera will fail in BasicClient::startCameraOps
2083 return;
2084 }
2085 mClientPackageName = packages[0];
2086 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002087}
2088
2089CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002090 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002091 mDestructionStarted = true;
2092}
2093
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002094binder::Status CameraService::BasicClient::disconnect() {
2095 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002096 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002097 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002098 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002099 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002100
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002101 sCameraService->removeByClient(this);
2102 sCameraService->logDisconnected(mCameraIdStr, mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002103 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08002104
2105 sp<IBinder> remote = getRemote();
2106 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002107 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002108 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002109
2110 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002111 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002112 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2113 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2114 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002115
Igor Murashkincba2c162013-03-20 15:56:31 -07002116 // client shouldn't be able to call into us anymore
2117 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002118
2119 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002120}
2121
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002122status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2123 // No dumping of clients directly over Binder,
2124 // must go through CameraService::dump
2125 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2126 IPCThreadState::self()->getCallingUid(), NULL, 0);
2127 return OK;
2128}
2129
Ruben Brunkcc776712015-02-17 20:18:47 -08002130String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002131 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002132}
2133
2134
2135int CameraService::BasicClient::getClientPid() const {
2136 return mClientPid;
2137}
2138
Ruben Brunk6267b532015-04-30 17:44:07 -07002139uid_t CameraService::BasicClient::getClientUid() const {
2140 return mClientUid;
2141}
2142
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002143bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2144 // Defaults to API2.
2145 return level == API_2;
2146}
2147
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002148status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002149 ATRACE_CALL();
2150
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002151 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002152 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002153 mOpsCallback = new OpsCallback(this);
2154
Igor Murashkine6800ce2013-03-04 17:25:57 -08002155 {
2156 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002157 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002158 }
2159
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002160 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002161 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002162 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002163 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002164
Svetoslav28e8ef72015-05-11 19:21:31 -07002165 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002166 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2167 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002168 return PERMISSION_DENIED;
2169 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002170
Svetoslav28e8ef72015-05-11 19:21:31 -07002171 if (res == AppOpsManager::MODE_IGNORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002172 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2173 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002174 // Return the same error as for device policy manager rejection
2175 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002176 }
2177
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002178 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002179
2180 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002181 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002182
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002183 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002184 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2185 mCameraIdStr);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002186
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002187 return OK;
2188}
2189
2190status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002191 ATRACE_CALL();
2192
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002193 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002194 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002195 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002196 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002197 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002198 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002199
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002200 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
2201 StatusInternal::ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002202
Ruben Brunkcc776712015-02-17 20:18:47 -08002203 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002204 sCameraService->updateStatus(StatusInternal::PRESENT,
2205 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002206
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002207 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002208 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2209 mCameraIdStr);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002210 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002211 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002212 if (mOpsCallback != NULL) {
2213 mAppOpsManager.stopWatchingMode(mOpsCallback);
2214 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002215 mOpsCallback.clear();
2216
2217 return OK;
2218}
2219
2220void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002221 ATRACE_CALL();
2222
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002223 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002224 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002225
2226 if (op != AppOpsManager::OP_CAMERA) {
2227 ALOGW("Unexpected app ops notification received: %d", op);
2228 return;
2229 }
2230
2231 int32_t res;
2232 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002233 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002234 ALOGV("checkOp returns: %d, %s ", res,
2235 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2236 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2237 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2238 "UNKNOWN");
2239
2240 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002241 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002242 myName.string());
2243 // Reset the client PID to allow server-initiated disconnect,
2244 // and to prevent further calls by client.
2245 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002246 CaptureResultExtras resultExtras; // a dummy result (invalid)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002247 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002248 disconnect();
2249 }
2250}
2251
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252// ----------------------------------------------------------------------------
2253
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002254void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002255 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002256 (void) errorCode;
2257 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002258 if (mRemoteCallback != NULL) {
2259 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2260 } else {
2261 ALOGE("mRemoteCallback is NULL!!");
2262 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002263}
2264
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002265// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002267 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002268 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002269}
2270
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002271bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2272 return level == API_1;
2273}
2274
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002275CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2276 mClient(client) {
2277}
2278
2279void CameraService::Client::OpsCallback::opChanged(int32_t op,
2280 const String16& packageName) {
2281 sp<BasicClient> client = mClient.promote();
2282 if (client != NULL) {
2283 client->opChanged(op, packageName);
2284 }
2285}
2286
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002288// CameraState
2289// ----------------------------------------------------------------------------
2290
2291CameraService::CameraState::CameraState(const String8& id, int cost,
2292 const std::set<String8>& conflicting) : mId(id),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002293 mStatus(StatusInternal::PRESENT), mCost(cost), mConflicting(conflicting) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08002294
2295CameraService::CameraState::~CameraState() {}
2296
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002297CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002298 Mutex::Autolock lock(mStatusLock);
2299 return mStatus;
2300}
2301
2302CameraParameters CameraService::CameraState::getShimParams() const {
2303 return mShimParams;
2304}
2305
2306void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2307 mShimParams = params;
2308}
2309
2310int CameraService::CameraState::getCost() const {
2311 return mCost;
2312}
2313
2314std::set<String8> CameraService::CameraState::getConflicting() const {
2315 return mConflicting;
2316}
2317
2318String8 CameraService::CameraState::getId() const {
2319 return mId;
2320}
2321
2322// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002323// ClientEventListener
2324// ----------------------------------------------------------------------------
2325
2326void CameraService::ClientEventListener::onClientAdded(
2327 const resource_policy::ClientDescriptor<String8,
2328 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002329 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002330 if (basicClient.get() != nullptr) {
2331 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2332 notifier.noteStartCamera(descriptor.getKey(),
2333 static_cast<int>(basicClient->getClientUid()));
2334 }
2335}
2336
2337void CameraService::ClientEventListener::onClientRemoved(
2338 const resource_policy::ClientDescriptor<String8,
2339 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002340 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002341 if (basicClient.get() != nullptr) {
2342 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2343 notifier.noteStopCamera(descriptor.getKey(),
2344 static_cast<int>(basicClient->getClientUid()));
2345 }
2346}
2347
2348
2349// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002350// CameraClientManager
2351// ----------------------------------------------------------------------------
2352
Ruben Brunk99e69712015-05-26 17:25:07 -07002353CameraService::CameraClientManager::CameraClientManager() {
2354 setListener(std::make_shared<ClientEventListener>());
2355}
2356
Ruben Brunkcc776712015-02-17 20:18:47 -08002357CameraService::CameraClientManager::~CameraClientManager() {}
2358
2359sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2360 const String8& id) const {
2361 auto descriptor = get(id);
2362 if (descriptor == nullptr) {
2363 return sp<BasicClient>{nullptr};
2364 }
2365 return descriptor->getValue();
2366}
2367
2368String8 CameraService::CameraClientManager::toString() const {
2369 auto all = getAll();
2370 String8 ret("[");
2371 bool hasAny = false;
2372 for (auto& i : all) {
2373 hasAny = true;
2374 String8 key = i->getKey();
2375 int32_t cost = i->getCost();
2376 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00002377 int32_t score = i->getPriority().getScore();
2378 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08002379 auto conflicting = i->getConflicting();
2380 auto clientSp = i->getValue();
2381 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002382 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002383 if (clientSp.get() != nullptr) {
2384 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002385 uid_t clientUid = clientSp->getClientUid();
2386 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002387 }
Emilian Peev8131a262017-02-01 12:33:43 +00002388 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
2389 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002390
Ruben Brunk6267b532015-04-30 17:44:07 -07002391 if (clientSp.get() != nullptr) {
2392 ret.appendFormat("User Id: %d, ", clientUserId);
2393 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002394 if (packageName.size() != 0) {
2395 ret.appendFormat("Client Package Name: %s", packageName.string());
2396 }
2397
2398 ret.append(", Conflicting Client Devices: {");
2399 for (auto& j : conflicting) {
2400 ret.appendFormat("%s, ", j.string());
2401 }
2402 ret.append("})");
2403 }
2404 if (hasAny) ret.append("\n");
2405 ret.append("]\n");
2406 return ret;
2407}
2408
2409CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2410 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00002411 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
2412 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002413
2414 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Emilian Peev8131a262017-02-01 12:33:43 +00002415 key, value, cost, conflictingKeys, score, ownerId, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002416}
2417
2418CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2419 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2420 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00002421 partial->getConflicting(), partial->getPriority().getScore(),
2422 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002423}
2424
2425// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426
2427static const int kDumpLockRetries = 50;
2428static const int kDumpLockSleep = 60000;
2429
2430static bool tryLock(Mutex& mutex)
2431{
2432 bool locked = false;
2433 for (int i = 0; i < kDumpLockRetries; ++i) {
2434 if (mutex.tryLock() == NO_ERROR) {
2435 locked = true;
2436 break;
2437 }
2438 usleep(kDumpLockSleep);
2439 }
2440 return locked;
2441}
2442
2443status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002444 ATRACE_CALL();
2445
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002447 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 getCallingPid(),
2449 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002450 return NO_ERROR;
2451 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002452 bool locked = tryLock(mServiceLock);
2453 // failed to lock - CameraService is probably deadlocked
2454 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002455 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002456 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002457
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002458 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002459 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07002460
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002461 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002462 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002463
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002464 if (locked) mServiceLock.unlock();
2465 return NO_ERROR;
2466 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002467 dprintf(fd, "\n== Service global info: ==\n\n");
2468 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
2469 dprintf(fd, "Number of normal camera devices: %d\n", mNumberOfNormalCameras);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002470 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002471 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
2472 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002473
2474 dumpEventLog(fd);
2475
2476 bool stateLocked = tryLock(mCameraStatesLock);
2477 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002478 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002479 }
2480
2481 for (auto& state : mCameraStates) {
2482 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002483
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002484 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002485
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002486 CameraParameters p = state.second->getShimParams();
2487 if (!p.isEmpty()) {
2488 dprintf(fd, " Camera1 API shim is using parameters:\n ");
2489 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002490 }
2491
2492 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08002493 if (clientDescriptor != nullptr) {
2494 dprintf(fd, " Device %s is open. Client instance dump:\n",
2495 cameraId.string());
2496 dprintf(fd, " Client priority score: %d state: %d\n",
2497 clientDescriptor->getPriority().getScore(),
2498 clientDescriptor->getPriority().getState());
2499 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
2500
2501 auto client = clientDescriptor->getValue();
2502 dprintf(fd, " Client package: %s\n",
2503 String8(client->getPackageName()).string());
2504
2505 client->dumpClient(fd, args);
2506 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002507 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002508 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002509 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002510
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002511 }
2512
2513 if (stateLocked) mCameraStatesLock.unlock();
2514
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002515 if (locked) mServiceLock.unlock();
2516
Emilian Peevf53f66e2017-04-11 14:29:43 +01002517 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002518
2519 dprintf(fd, "\n== Vendor tags: ==\n\n");
2520
2521 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2522 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00002523 sp<VendorTagDescriptorCache> cache =
2524 VendorTagDescriptorCache::getGlobalVendorTagCache();
2525 if (cache == NULL) {
2526 dprintf(fd, "No vendor tags.\n");
2527 } else {
2528 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
2529 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002530 } else {
2531 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
2532 }
2533
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002534 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002535 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002536 camera3::CameraTraces::dump(fd, args);
2537
2538 // Process dump arguments, if any
2539 int n = args.size();
2540 String16 verboseOption("-v");
2541 String16 unreachableOption("--unreachable");
2542 for (int i = 0; i < n; i++) {
2543 if (args[i] == verboseOption) {
2544 // change logging level
2545 if (i + 1 >= n) continue;
2546 String8 levelStr(args[i+1]);
2547 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002548 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002549 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002550 } else if (args[i] == unreachableOption) {
2551 // Dump memory analysis
2552 // TODO - should limit be an argument parameter?
2553 UnreachableMemoryInfo info;
2554 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
2555 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002556 dprintf(fd, "\n== Unable to dump unreachable memory. "
2557 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002558 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002559 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002560 std::string s = info.ToString(/*log_contents*/ true);
2561 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 }
2563 }
2564 }
2565 return NO_ERROR;
2566}
2567
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002568void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002569 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002570
2571 Mutex::Autolock l(mLogLock);
2572 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002573 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002574 }
2575
2576 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002577 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002578 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002579 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002580 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002581 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002582}
2583
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002584void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002585 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002586 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2587 if (mTorchClientMap[i] == who) {
2588 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002589 String8 cameraId = mTorchClientMap.keyAt(i);
2590 status_t res = mFlashlight->setTorchMode(cameraId, false);
2591 if (res) {
2592 ALOGE("%s: torch client died but couldn't turn off torch: "
2593 "%s (%d)", __FUNCTION__, strerror(-res), res);
2594 return;
2595 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002596 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002597 break;
2598 }
2599 }
2600}
2601
Ruben Brunkcc776712015-02-17 20:18:47 -08002602/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002603
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002604 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002605 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2606 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002607 */
2608
Ruben Brunka8ca9152015-04-07 14:23:40 -07002609 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2610
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002611 // check torch client
2612 handleTorchClientBinderDied(who);
2613
2614 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002615 if(!evictClientIdByRemote(who)) {
2616 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002617 return;
2618 }
2619
Ruben Brunkcc776712015-02-17 20:18:47 -08002620 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2621 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002622}
2623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002624void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002625 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002626}
2627
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002628void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
2629 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002630 // Do not lock mServiceLock here or can get into a deadlock from
2631 // connect() -> disconnect -> updateStatus
2632
2633 auto state = getCameraState(cameraId);
2634
2635 if (state == nullptr) {
2636 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2637 cameraId.string());
2638 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002639 }
2640
Ruben Brunkcc776712015-02-17 20:18:47 -08002641 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2642 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2643 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002644 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002645
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002646 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002647 // Update torch status if it has a flash unit.
2648 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002649 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002650 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2651 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002652 TorchModeStatus newTorchStatus =
2653 status == StatusInternal::PRESENT ?
2654 TorchModeStatus::AVAILABLE_OFF :
2655 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002656 if (torchStatus != newTorchStatus) {
2657 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2658 }
2659 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002660 }
2661
2662 Mutex::Autolock lock(mStatusListenerLock);
2663
2664 for (auto& listener : mListenerList) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002665 listener->onStatusChanged(mapToInterface(status), String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08002666 }
2667 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002668}
2669
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002670template<class Func>
2671void CameraService::CameraState::updateStatus(StatusInternal status,
2672 const String8& cameraId,
2673 std::initializer_list<StatusInternal> rejectSourceStates,
2674 Func onStatusUpdatedLocked) {
2675 Mutex::Autolock lock(mStatusLock);
2676 StatusInternal oldStatus = mStatus;
2677 mStatus = status;
2678
2679 if (oldStatus == status) {
2680 return;
2681 }
2682
2683 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
2684 cameraId.string(), oldStatus, status);
2685
2686 if (oldStatus == StatusInternal::NOT_PRESENT &&
2687 (status != StatusInternal::PRESENT &&
2688 status != StatusInternal::ENUMERATING)) {
2689
2690 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
2691 __FUNCTION__);
2692 mStatus = oldStatus;
2693 return;
2694 }
2695
2696 /**
2697 * Sometimes we want to conditionally do a transition.
2698 * For example if a client disconnects, we want to go to PRESENT
2699 * only if we weren't already in NOT_PRESENT or ENUMERATING.
2700 */
2701 for (auto& rejectStatus : rejectSourceStates) {
2702 if (oldStatus == rejectStatus) {
2703 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
2704 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
2705 mStatus = oldStatus;
2706 return;
2707 }
2708 }
2709
2710 onStatusUpdatedLocked(cameraId, status);
2711}
2712
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002713void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2714 const String8& cameraId) {
2715 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2716 if (proxyBinder == nullptr) return;
2717 String16 id(cameraId);
2718 proxyBinder->notifyCameraState(id, newState);
2719}
2720
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002721status_t CameraService::getTorchStatusLocked(
2722 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002723 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002724 if (!status) {
2725 return BAD_VALUE;
2726 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002727 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2728 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002729 // invalid camera ID or the camera doesn't have a flash unit
2730 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002731 }
2732
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002733 *status = mTorchStatusMap.valueAt(index);
2734 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002735}
2736
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002737status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002738 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002739 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2740 if (index == NAME_NOT_FOUND) {
2741 return BAD_VALUE;
2742 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002743 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002744
2745 return OK;
2746}
2747
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748}; // namespace android