blob: 45ef1f857dfcb28c9f3e13a7f6bdfbbade641bba [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 Talvalaceb388d2013-02-19 10:40:14 -080031#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryBase.h>
35#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080036#include <binder/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070038#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080039#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <hardware/hardware.h>
41#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080042#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070044#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/Errors.h>
46#include <utils/Log.h>
47#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080048#include <utils/Trace.h>
49#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070050#include <system/camera_metadata.h>
51#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070054#include "api1/CameraClient.h"
55#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070057#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070058#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
60namespace android {
61
62// ----------------------------------------------------------------------------
63// Logging support -- this is for debugging only
64// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070065volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Steve Blockb8a80522011-12-20 16:23:08 +000067#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
70static void setLogLevel(int level) {
71 android_atomic_write(level, &gLogLevel);
72}
73
74// ----------------------------------------------------------------------------
75
Igor Murashkincba2c162013-03-20 15:56:31 -070076extern "C" {
77static void camera_device_status_change(
78 const struct camera_module_callbacks* callbacks,
79 int camera_id,
80 int new_status) {
81 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080082 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070083
Bin Chene16d1162016-02-22 18:19:58 +110084 cs->onDeviceStatusChanged(camera_id,
Ruben Brunkcc776712015-02-17 20:18:47 -080085 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070086}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080087
88static void torch_mode_status_change(
89 const struct camera_module_callbacks* callbacks,
90 const char* camera_id,
91 int new_status) {
92 if (!callbacks || !camera_id) {
93 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
94 callbacks, camera_id);
95 }
96 sp<CameraService> cs = const_cast<CameraService*>(
97 static_cast<const CameraService*>(callbacks));
98
99 ICameraServiceListener::TorchStatus status;
100 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800101 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800102 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
103 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800104 case TORCH_MODE_STATUS_AVAILABLE_OFF:
105 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
106 break;
107 case TORCH_MODE_STATUS_AVAILABLE_ON:
108 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800109 break;
110 default:
111 ALOGE("Unknown torch status %d", new_status);
112 return;
113 }
114
115 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800116 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800117 status);
118}
Igor Murashkincba2c162013-03-20 15:56:31 -0700119} // extern "C"
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
123// This is ugly and only safe if we never re-create the CameraService, but
124// should be ok for now.
125static CameraService *gCameraService;
126
Ruben Brunk6267b532015-04-30 17:44:07 -0700127CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH), mAllowedUsers(),
128 mSoundRef(0), mModule(0), mFlashlight(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000129 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800131
Igor Murashkincba2c162013-03-20 15:56:31 -0700132 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800133 this->torch_mode_status_change = android::torch_mode_status_change;
134
Ruben Brunkcc776712015-02-17 20:18:47 -0800135 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136}
137
Iliyan Malchev8951a972011-04-14 16:55:59 -0700138void CameraService::onFirstRef()
139{
Ruben Brunkcc776712015-02-17 20:18:47 -0800140 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800141
Iliyan Malchev8951a972011-04-14 16:55:59 -0700142 BnCameraService::onFirstRef();
143
Ruben Brunk99e69712015-05-26 17:25:07 -0700144 // Update battery life tracking if service is restarting
145 BatteryNotifier& notifier(BatteryNotifier::getInstance());
146 notifier.noteResetCamera();
147 notifier.noteResetFlashlight();
148
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800149 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700150 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
151 (const hw_module_t **)&rawModule);
152 if (err < 0) {
153 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
154 logServiceError("Could not load camera HAL module", err);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700155 mNumberOfCameras = 0;
Yin-Chia Yeh6dd6c542015-12-07 12:20:11 -0800156 mNumberOfNormalCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700157 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700158 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800159
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700161 err = mModule->init();
162 if (err != OK) {
163 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
164 strerror(-err));
165 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800166
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700167 mNumberOfCameras = 0;
168 delete mModule;
169 mModule = nullptr;
170 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700171 }
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700172 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700173
174 mNumberOfCameras = mModule->getNumberOfCameras();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700175 mNumberOfNormalCameras = mNumberOfCameras;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700176
Yin-Chia Yehd4a653a2015-10-14 11:05:44 -0700177 // Setup vendor tags before we call get_camera_info the first time
178 // because HAL might need to setup static vendor keys in get_camera_info
179 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
180 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
181 setUpVendorTags();
182 }
183
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700184 mFlashlight = new CameraFlashlight(*mModule, *this);
185 status_t res = mFlashlight->findFlashUnits();
186 if (res) {
187 // impossible because we haven't open any camera devices.
188 ALOGE("Failed to find flash units.");
189 }
190
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700191 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700192 for (int i = 0; i < mNumberOfCameras; i++) {
193 String8 cameraId = String8::format("%d", i);
194
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700195 // Get camera info
196
197 struct camera_info info;
198 bool haveInfo = true;
199 status_t rc = mModule->getCameraInfo(i, &info);
200 if (rc != NO_ERROR) {
201 ALOGE("%s: Received error loading camera info for device %d, cost and"
202 " conflicting devices fields set to defaults for this device.",
203 __FUNCTION__, i);
204 haveInfo = false;
205 }
206
207 // Check for backwards-compatibility support
208 if (haveInfo) {
209 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
210 delete mModule;
211 mModule = nullptr;
212 return;
213 }
214 }
215
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700216 // Defaults to use for cost and conflicting devices
217 int cost = 100;
218 char** conflicting_devices = nullptr;
219 size_t conflicting_devices_length = 0;
220
221 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700222 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
223 cost = info.resource_cost;
224 conflicting_devices = info.conflicting_devices;
225 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700226 }
227
228 std::set<String8> conflicting;
229 for (size_t i = 0; i < conflicting_devices_length; i++) {
230 conflicting.emplace(String8(conflicting_devices[i]));
231 }
232
233 // Initialize state for each camera device
234 {
235 Mutex::Autolock lock(mCameraStatesLock);
236 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
237 conflicting));
238 }
239
240 if (mFlashlight->hasFlashUnit(cameraId)) {
241 mTorchStatusMap.add(cameraId,
242 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
243 }
244 }
245
246 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
247 mModule->setCallbacks(this);
248 }
249
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700250 CameraDeviceFactory::registerService(this);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700251
252 CameraService::pingCameraServiceProxy();
253}
254
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700255sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800256 sp<ICameraServiceProxy> proxyBinder = nullptr;
257#ifndef __BRILLO__
Ruben Brunk2823ce02015-05-19 17:25:13 -0700258 sp<IServiceManager> sm = defaultServiceManager();
259 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800260 if (binder != nullptr) {
261 proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700262 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800263#endif
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700264 return proxyBinder;
265}
266
267void CameraService::pingCameraServiceProxy() {
268 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
269 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700270 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700271}
272
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800274 if (mModule) {
275 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800276 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800277 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800278 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800279 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700280}
281
Bin Chene16d1162016-02-22 18:19:58 +1100282void CameraService::onDeviceStatusChanged(int cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800283 camera_device_status_t newStatus) {
284 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700285 cameraId, newStatus);
286
Ruben Brunkcc776712015-02-17 20:18:47 -0800287 String8 id = String8::format("%d", cameraId);
288 std::shared_ptr<CameraState> state = getCameraState(id);
289
290 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700291 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
292 return;
293 }
294
Ruben Brunkcc776712015-02-17 20:18:47 -0800295 ICameraServiceListener::Status oldStatus = state->getStatus();
296
297 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
298 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700299 return;
300 }
301
Igor Murashkincba2c162013-03-20 15:56:31 -0700302 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700303 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
304 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800305 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700306 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800307 // Don't do this in updateStatus to avoid deadlock over mServiceLock
308 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700309
Ruben Brunkcc776712015-02-17 20:18:47 -0800310 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
311 // to this device until the status changes
312 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700313
Ruben Brunkcc776712015-02-17 20:18:47 -0800314 // Remove cached shim parameters
315 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700316
Ruben Brunkcc776712015-02-17 20:18:47 -0800317 // Remove the client from the list of active clients
318 clientToDisconnect = removeClientLocked(id);
319
320 // Notify the client of disconnection
Tom Keel5adc76c2015-10-08 16:42:56 +0200321 if (clientToDisconnect != nullptr) {
322 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
323 CaptureResultExtras{});
324 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700325 }
326
Ruben Brunkcc776712015-02-17 20:18:47 -0800327 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
328 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700329
Ruben Brunkcc776712015-02-17 20:18:47 -0800330 // Disconnect client
331 if (clientToDisconnect.get() != nullptr) {
332 // Ensure not in binder RPC so client disconnect PID checks work correctly
333 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
334 "onDeviceStatusChanged must be called from the camera service process!");
335 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700336 }
337
Ruben Brunkcc776712015-02-17 20:18:47 -0800338 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700339 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
340 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
341 newStatus));
342 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800343 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700344 }
345
Igor Murashkincba2c162013-03-20 15:56:31 -0700346}
347
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800348void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800349 ICameraServiceListener::TorchStatus newStatus) {
350 Mutex::Autolock al(mTorchStatusMutex);
351 onTorchStatusChangedLocked(cameraId, newStatus);
352}
353
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800354void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800355 ICameraServiceListener::TorchStatus newStatus) {
356 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
357 __FUNCTION__, cameraId.string(), newStatus);
358
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800359 ICameraServiceListener::TorchStatus status;
360 status_t res = getTorchStatusLocked(cameraId, &status);
361 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700362 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
363 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800364 return;
365 }
366 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800367 return;
368 }
369
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800370 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800371 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700372 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800373 return;
374 }
375
Ruben Brunkcc776712015-02-17 20:18:47 -0800376 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700377 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700378 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700379 auto iter = mTorchUidMap.find(cameraId);
380 if (iter != mTorchUidMap.end()) {
381 int oldUid = iter->second.second;
382 int newUid = iter->second.first;
383 BatteryNotifier& notifier(BatteryNotifier::getInstance());
384 if (oldUid != newUid) {
385 // If the UID has changed, log the status and update current UID in mTorchUidMap
386 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
387 notifier.noteFlashlightOff(cameraId, oldUid);
388 }
389 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
390 notifier.noteFlashlightOn(cameraId, newUid);
391 }
392 iter->second.second = newUid;
393 } else {
394 // If the UID has not changed, log the status
395 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
396 notifier.noteFlashlightOn(cameraId, oldUid);
397 } else {
398 notifier.noteFlashlightOff(cameraId, oldUid);
399 }
400 }
401 }
402 }
403
404 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800405 Mutex::Autolock lock(mStatusListenerLock);
406 for (auto& i : mListenerList) {
407 i->onTorchStatusChanged(newStatus, String16{cameraId});
408 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800409 }
410}
411
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700413 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700414 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
415}
416
417int32_t CameraService::getNumberOfCameras(int type) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700418 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700419 switch (type) {
420 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
421 return mNumberOfNormalCameras;
422 case CAMERA_TYPE_ALL:
423 return mNumberOfCameras;
424 default:
425 ALOGW("%s: Unknown camera type %d, returning 0",
426 __FUNCTION__, type);
427 return 0;
428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429}
430
431status_t CameraService::getCameraInfo(int cameraId,
432 struct CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700433 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700434 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700435 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700436 }
437
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
439 return BAD_VALUE;
440 }
441
Iliyan Malchev8951a972011-04-14 16:55:59 -0700442 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700443 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800444 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700445 cameraInfo->facing = info.facing;
446 cameraInfo->orientation = info.orientation;
447 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448}
449
Ruben Brunkcc776712015-02-17 20:18:47 -0800450int CameraService::cameraIdToInt(const String8& cameraId) {
451 errno = 0;
452 size_t pos = 0;
453 int ret = stoi(std::string{cameraId.string()}, &pos);
454 if (errno != 0 || pos != cameraId.size()) {
455 return -1;
456 }
457 return ret;
458}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700459
460status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700461 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700462 status_t ret = OK;
463 struct CameraInfo info;
464 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
465 return ret;
466 }
467
468 CameraMetadata shimInfo;
469 int32_t orientation = static_cast<int32_t>(info.orientation);
470 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
471 return ret;
472 }
473
474 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
475 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
476 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
477 return ret;
478 }
479
Igor Murashkin65d14b92014-06-17 12:03:20 -0700480 CameraParameters shimParams;
481 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
482 // Error logged by callee
483 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700484 }
485
486 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700487 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700488 Vector<int32_t> formats;
489 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700490 {
491 shimParams.getSupportedPreviewSizes(/*out*/sizes);
492 shimParams.getSupportedPreviewFormats(/*out*/formats);
493 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700494 }
495
496 // Always include IMPLEMENTATION_DEFINED
497 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
498
499 const size_t INTS_PER_CONFIG = 4;
500
501 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700502 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
503
504 Vector<int32_t> streamConfigs;
505 streamConfigs.setCapacity(streamConfigSize);
506
Ruben Brunkb2119af2014-05-09 19:57:56 -0700507 for (size_t i = 0; i < formats.size(); ++i) {
508 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700509 streamConfigs.add(formats[i]);
510 streamConfigs.add(sizes[j].width);
511 streamConfigs.add(sizes[j].height);
512 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700513 }
514 }
515
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700516 for (size_t i = 0; i < jpegSizes.size(); ++i) {
517 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
518 streamConfigs.add(jpegSizes[i].width);
519 streamConfigs.add(jpegSizes[i].height);
520 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
521 }
522
Ruben Brunkb2119af2014-05-09 19:57:56 -0700523 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700524 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700525 return ret;
526 }
527
528 int64_t fakeMinFrames[0];
529 // TODO: Fixme, don't fake min frame durations.
530 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
531 fakeMinFrames, 0)) != OK) {
532 return ret;
533 }
534
535 int64_t fakeStalls[0];
536 // TODO: Fixme, don't fake stall durations.
537 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
538 fakeStalls, 0)) != OK) {
539 return ret;
540 }
541
542 *cameraInfo = shimInfo;
543 return OK;
544}
545
Zhijun He2b59be82013-09-25 10:14:30 -0700546status_t CameraService::getCameraCharacteristics(int cameraId,
547 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700548 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700549 if (!cameraInfo) {
550 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
551 return BAD_VALUE;
552 }
553
554 if (!mModule) {
555 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
556 return -ENODEV;
557 }
558
Zhijun He2b59be82013-09-25 10:14:30 -0700559 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
560 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
561 return BAD_VALUE;
562 }
563
564 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700565 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800566 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700567 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
568 /**
569 * Backwards compatibility mode for old HALs:
570 * - Convert CameraInfo into static CameraMetadata properties.
571 * - Retrieve cached CameraParameters for this camera. If none exist,
572 * attempt to open CameraClient and retrieve the CameraParameters.
573 * - Convert cached CameraParameters into static CameraMetadata
574 * properties.
575 */
576 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700577
Ruben Brunkb2119af2014-05-09 19:57:56 -0700578 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
579 return ret;
580 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700581
Ruben Brunkb2119af2014-05-09 19:57:56 -0700582 } else {
583 /**
584 * Normal HAL 2.1+ codepath.
585 */
586 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800587 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700588 *cameraInfo = info.static_camera_characteristics;
589 }
Zhijun He2b59be82013-09-25 10:14:30 -0700590
591 return ret;
592}
593
Ruben Brunkcc776712015-02-17 20:18:47 -0800594int CameraService::getCallingPid() {
595 return IPCThreadState::self()->getCallingPid();
596}
597
598int CameraService::getCallingUid() {
599 return IPCThreadState::self()->getCallingUid();
600}
601
602String8 CameraService::getFormattedCurrentTime() {
603 time_t now = time(nullptr);
604 char formattedTime[64];
605 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
606 return String8(formattedTime);
607}
608
609int CameraService::getCameraPriorityFromProcState(int procState) {
610 // Find the priority for the camera usage based on the process state. Higher priority clients
611 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700612 if (procState < 0) {
613 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
614 procState);
615 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800616 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700617 // Treat sleeping TOP processes the same as regular TOP processes, for
618 // access priority. This is important for lock-screen camera launch scenarios
619 if (procState == PROCESS_STATE_TOP_SLEEPING) {
620 procState = PROCESS_STATE_TOP;
621 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700622 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800623}
624
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800625status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700626 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800627 if (!mModule) {
628 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
629 return -ENODEV;
630 }
631
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800632 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
633 return OK;
634}
635
Igor Murashkin634a5152013-02-20 17:15:11 -0800636int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700637 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800638 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800639 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800640 return -1;
641 }
642
643 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800644 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800645 deviceVersion = info.device_version;
646 } else {
647 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
648 }
649
650 if (facing) {
651 *facing = info.facing;
652 }
653
654 return deviceVersion;
655}
656
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700657status_t CameraService::filterGetInfoErrorCode(status_t err) {
658 switch(err) {
659 case NO_ERROR:
660 case -EINVAL:
661 return err;
662 default:
663 break;
664 }
665 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800666}
667
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800668bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700669 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800670 vendor_tag_ops_t vOps = vendor_tag_ops_t();
671
672 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800673 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800674 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
675 return false;
676 }
677
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800678 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800679
680 // Ensure all vendor operations are present
681 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
682 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
683 vOps.get_tag_type == NULL) {
684 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
685 , __FUNCTION__);
686 return false;
687 }
688
689 // Read all vendor tag definitions into a descriptor
690 sp<VendorTagDescriptor> desc;
691 status_t res;
692 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
693 != OK) {
694 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
695 "received error %s (%d). Camera clients will not be able to use"
696 "vendor tags", __FUNCTION__, strerror(res), res);
697 return false;
698 }
699
700 // Set the global descriptor to use with camera metadata
701 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
702 return true;
703}
704
Ruben Brunkcc776712015-02-17 20:18:47 -0800705status_t CameraService::makeClient(const sp<CameraService>& cameraService,
706 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
707 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
708 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
709 /*out*/sp<BasicClient>* client) {
710
711 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
712 int id = cameraIdToInt(cameraId);
713 if (id == -1) {
714 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
715 cameraId.string());
716 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700717 }
718
Ruben Brunkcc776712015-02-17 20:18:47 -0800719 if (halVersion < 0 || halVersion == deviceVersion) {
720 // Default path: HAL version is unspecified by caller, create CameraClient
721 // based on device version reported by the HAL.
722 switch(deviceVersion) {
723 case CAMERA_DEVICE_API_VERSION_1_0:
724 if (effectiveApiLevel == API_1) { // Camera1 API route
725 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
726 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
727 clientPid, clientUid, getpid(), legacyMode);
728 } else { // Camera2 API route
729 ALOGW("Camera using old HAL version: %d", deviceVersion);
730 return -EOPNOTSUPP;
731 }
732 break;
733 case CAMERA_DEVICE_API_VERSION_2_0:
734 case CAMERA_DEVICE_API_VERSION_2_1:
735 case CAMERA_DEVICE_API_VERSION_3_0:
736 case CAMERA_DEVICE_API_VERSION_3_1:
737 case CAMERA_DEVICE_API_VERSION_3_2:
738 case CAMERA_DEVICE_API_VERSION_3_3:
739 if (effectiveApiLevel == API_1) { // Camera1 API route
740 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
741 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
742 clientPid, clientUid, servicePid, legacyMode);
743 } else { // Camera2 API route
744 sp<ICameraDeviceCallbacks> tmp =
745 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
746 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
747 facing, clientPid, clientUid, servicePid);
748 }
749 break;
750 default:
751 // Should not be reachable
752 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
753 return INVALID_OPERATION;
754 }
755 } else {
756 // A particular HAL version is requested by caller. Create CameraClient
757 // based on the requested HAL version.
758 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
759 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
760 // Only support higher HAL version device opened as HAL1.0 device.
761 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
762 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
763 clientPid, clientUid, servicePid, legacyMode);
764 } else {
765 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
766 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
767 " opened as HAL %x device", halVersion, deviceVersion,
768 CAMERA_DEVICE_API_VERSION_1_0);
769 return INVALID_OPERATION;
770 }
771 }
772 return NO_ERROR;
773}
774
Ruben Brunk6267b532015-04-30 17:44:07 -0700775String8 CameraService::toString(std::set<userid_t> intSet) {
776 String8 s("");
777 bool first = true;
778 for (userid_t i : intSet) {
779 if (first) {
780 s.appendFormat("%d", i);
781 first = false;
782 } else {
783 s.appendFormat(", %d", i);
784 }
785 }
786 return s;
787}
788
Ruben Brunkcc776712015-02-17 20:18:47 -0800789status_t CameraService::initializeShimMetadata(int cameraId) {
790 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700791
792 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800793 String8 id = String8::format("%d", cameraId);
794 status_t ret = NO_ERROR;
795 sp<Client> tmp = nullptr;
796 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
797 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
798 false, true, tmp)) != NO_ERROR) {
799 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
800 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700801 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800802 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700803}
804
Igor Murashkin65d14b92014-06-17 12:03:20 -0700805status_t CameraService::getLegacyParametersLazy(int cameraId,
806 /*out*/
807 CameraParameters* parameters) {
808
809 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
810
811 status_t ret = 0;
812
813 if (parameters == NULL) {
814 ALOGE("%s: parameters must not be null", __FUNCTION__);
815 return BAD_VALUE;
816 }
817
Ruben Brunkcc776712015-02-17 20:18:47 -0800818 String8 id = String8::format("%d", cameraId);
819
820 // Check if we already have parameters
821 {
822 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700823 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800824 auto cameraState = getCameraState(id);
825 if (cameraState == nullptr) {
826 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
827 return BAD_VALUE;
828 }
829 CameraParameters p = cameraState->getShimParams();
830 if (!p.isEmpty()) {
831 *parameters = p;
832 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700833 }
834 }
835
Ruben Brunkcc776712015-02-17 20:18:47 -0800836 int64_t token = IPCThreadState::self()->clearCallingIdentity();
837 ret = initializeShimMetadata(cameraId);
838 IPCThreadState::self()->restoreCallingIdentity(token);
839 if (ret != NO_ERROR) {
840 // Error already logged by callee
841 return ret;
842 }
843
844 // Check for parameters again
845 {
846 // Scope for service lock
847 Mutex::Autolock lock(mServiceLock);
848 auto cameraState = getCameraState(id);
849 if (cameraState == nullptr) {
850 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
851 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700852 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800853 CameraParameters p = cameraState->getShimParams();
854 if (!p.isEmpty()) {
855 *parameters = p;
856 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700857 }
858 }
859
Ruben Brunkcc776712015-02-17 20:18:47 -0800860 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
861 __FUNCTION__);
862 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700863}
864
Ruben Brunk36597b22015-03-20 22:15:57 -0700865status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
866 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800867
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500869
Iliyan Malchev8951a972011-04-14 16:55:59 -0700870 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800871 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
872 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700873 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700874 }
875
Ruben Brunkcc776712015-02-17 20:18:47 -0800876 if (getCameraState(cameraId) == nullptr) {
877 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
878 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700879 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 }
881
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800882#if !defined(__BRILLO__)
883 status_t allowed = validateClientPermissionsLocked(cameraId, clientUid);
884 if (allowed != OK) {
885 return allowed;
886 }
887#endif // defined(__BRILLO__)
888
889 return checkIfDeviceIsUsable(cameraId);
890}
891
892status_t CameraService::validateClientPermissionsLocked(const String8& cameraId, int& clientUid)
893 const {
894 int callingPid = getCallingPid();
895
896 if (clientUid == USE_CALLING_UID) {
897 clientUid = getCallingUid();
898 } else {
899 // We only trust our own process to forward client UIDs
900 if (callingPid != getpid()) {
901 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
902 callingPid, clientUid);
903 return PERMISSION_DENIED;
904 }
905 }
906
Ruben Brunkcc776712015-02-17 20:18:47 -0800907 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800908 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800909 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700910 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800911 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
912 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800913 if (strcmp(value, "1") == 0) {
914 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800915 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
916 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700917 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800918 }
919
Ruben Brunka8ca9152015-04-07 14:23:40 -0700920 // Only allow clients who are being used by the current foreground device user, unless calling
921 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700922 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
923 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
924 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
925 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700926 return PERMISSION_DENIED;
927 }
928
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800929 return OK;
Ruben Brunkcc776712015-02-17 20:18:47 -0800930}
931
932status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
933 auto cameraState = getCameraState(cameraId);
934 int callingPid = getCallingPid();
935 if (cameraState == nullptr) {
936 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
937 cameraId.string());
938 return -ENODEV;
939 }
940
941 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700942 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800943 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
944 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700945 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700946 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800947 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
948 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700949 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700950 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700951
Ruben Brunkcc776712015-02-17 20:18:47 -0800952 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800953}
954
Ruben Brunkcc776712015-02-17 20:18:47 -0800955void CameraService::finishConnectLocked(const sp<BasicClient>& client,
956 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800957
Ruben Brunkcc776712015-02-17 20:18:47 -0800958 // Make a descriptor for the incoming client
959 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
960 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
961
962 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
963 String8(client->getPackageName()));
964
965 if (evicted.size() > 0) {
966 // This should never happen - clients should already have been removed in disconnect
967 for (auto& i : evicted) {
968 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
969 __FUNCTION__, i->getKey().string());
970 }
971
972 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
973 __FUNCTION__);
974 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700975
976 // And register a death notification for the client callback. Do
977 // this last to avoid Binder policy where a nested Binder
978 // transaction might be pre-empted to service the client death
979 // notification if the client process dies before linkToDeath is
980 // invoked.
981 sp<IBinder> remoteCallback = client->getRemote();
982 if (remoteCallback != nullptr) {
983 remoteCallback->linkToDeath(this);
984 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800985}
986
987status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
988 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
989 /*out*/
990 sp<BasicClient>* client,
991 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700992 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800993 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700994 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800995 DescriptorPtr clientDescriptor;
996 {
997 if (effectiveApiLevel == API_1) {
998 // If we are using API1, any existing client for this camera ID with the same remote
999 // should be returned rather than evicted to allow MediaRecorder to work properly.
1000
1001 auto current = mActiveClientManager.get(cameraId);
1002 if (current != nullptr) {
1003 auto clientSp = current->getValue();
1004 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001005 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1006 ALOGW("CameraService connect called from same client, but with a different"
1007 " API level, evicting prior client...");
1008 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001009 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001010 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001011 *client = clientSp;
1012 return NO_ERROR;
1013 }
1014 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001015 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001016 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001017
Ruben Brunkcc776712015-02-17 20:18:47 -08001018 // Return error if the device was unplugged or removed by the HAL for some reason
1019 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1020 return ret;
1021 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001022
Ruben Brunkcc776712015-02-17 20:18:47 -08001023 // Get current active client PIDs
1024 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1025 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001026
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001027 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1028 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1029 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1030 // not have an out-of-class definition.
1031 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001032
Ruben Brunkcc776712015-02-17 20:18:47 -08001033 // Get priorites of all active PIDs
1034 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1035 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001036
Ruben Brunkcc776712015-02-17 20:18:47 -08001037 // Update all active clients' priorities
1038 std::map<int,int> pidToPriorityMap;
1039 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1040 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1041 }
1042 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001043
Ruben Brunkcc776712015-02-17 20:18:47 -08001044 // Get state for the given cameraId
1045 auto state = getCameraState(cameraId);
1046 if (state == nullptr) {
1047 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1048 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001049 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001050 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001051
1052 // Make descriptor for incoming client
1053 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1054 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1055 state->getConflicting(),
1056 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1057
1058 // Find clients that would be evicted
1059 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1060
1061 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1062 // background, so we cannot do evictions
1063 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1064 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1065 " priority).", clientPid);
1066
1067 sp<BasicClient> clientSp = clientDescriptor->getValue();
1068 String8 curTime = getFormattedCurrentTime();
1069 auto incompatibleClients =
1070 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1071
1072 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001073 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001074 cameraId.string(), packageName.string(), clientPid,
1075 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1076
1077 for (auto& i : incompatibleClients) {
1078 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1079 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1080 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1081 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001082 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1083 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1084 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1085 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001086 }
1087
1088 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001089 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001090 mEventLog.add(msg);
1091
1092 return -EBUSY;
1093 }
1094
1095 for (auto& i : evicted) {
1096 sp<BasicClient> clientSp = i->getValue();
1097 if (clientSp.get() == nullptr) {
1098 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1099
1100 // TODO: Remove this
1101 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1102 __FUNCTION__);
1103 mActiveClientManager.remove(i);
1104 continue;
1105 }
1106
1107 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1108 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001109 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001110
Ruben Brunkcc776712015-02-17 20:18:47 -08001111 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001112 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1113 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1114 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001115 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1116 i->getOwnerId(), i->getPriority(), cameraId.string(),
1117 packageName.string(), clientPid,
1118 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1119
1120 // Notify the client of disconnection
1121 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1122 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001123 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001124 }
1125
Ruben Brunkcc776712015-02-17 20:18:47 -08001126 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1127 // other clients from connecting in mServiceLockWrapper if held
1128 mServiceLock.unlock();
1129
1130 // Clear caller identity temporarily so client disconnect PID checks work correctly
1131 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1132
1133 // Destroy evicted clients
1134 for (auto& i : evictedClients) {
1135 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001136 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001137 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001138
1139 IPCThreadState::self()->restoreCallingIdentity(token);
1140
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001141 for (const auto& i : evictedClients) {
1142 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1143 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1144 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1145 if (ret == TIMED_OUT) {
1146 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1147 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1148 mActiveClientManager.toString().string());
1149 return -EBUSY;
1150 }
1151 if (ret != NO_ERROR) {
1152 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1153 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1154 ret, mActiveClientManager.toString().string());
1155 return ret;
1156 }
1157 }
1158
1159 evictedClients.clear();
1160
Ruben Brunkcc776712015-02-17 20:18:47 -08001161 // Once clients have been disconnected, relock
1162 mServiceLock.lock();
1163
1164 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1165 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1166 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001167 }
1168
Ruben Brunkcc776712015-02-17 20:18:47 -08001169 *partial = clientDescriptor;
1170 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001171}
1172
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001173status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001174 const sp<ICameraClient>& cameraClient,
1175 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001176 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001177 int clientUid,
1178 /*out*/
1179 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001180
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001181 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 status_t ret = NO_ERROR;
1183 String8 id = String8::format("%d", cameraId);
1184 sp<Client> client = nullptr;
1185 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001186 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001187
Ruben Brunkcc776712015-02-17 20:18:47 -08001188 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001189 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001190 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001191 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 }
1193
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001194 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001195 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196}
1197
Zhijun Heb10cdad2014-06-16 16:38:35 -07001198status_t CameraService::connectLegacy(
1199 const sp<ICameraClient>& cameraClient,
1200 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001201 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001202 int clientUid,
1203 /*out*/
1204 sp<ICamera>& device) {
1205
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001206 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001207 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001208 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001209 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001210 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001211 /*
1212 * Either the HAL version is unspecified in which case this just creates
1213 * a camera client selected by the latest device version, or
1214 * it's a particular version in which case the HAL must supported
1215 * the open_legacy call
1216 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001217 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001218 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001219 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001220 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001221 return INVALID_OPERATION;
1222 }
1223
Ruben Brunkcc776712015-02-17 20:18:47 -08001224 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001226 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001227 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001228
Ruben Brunkcc776712015-02-17 20:18:47 -08001229 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001230 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001231 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001232 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001233 }
1234
Zhijun Heb10cdad2014-06-16 16:38:35 -07001235 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001236 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001237}
1238
Ruben Brunkcc776712015-02-17 20:18:47 -08001239status_t CameraService::connectDevice(
1240 const sp<ICameraDeviceCallbacks>& cameraCb,
1241 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001242 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001243 int clientUid,
1244 /*out*/
1245 sp<ICameraDeviceUser>& device) {
1246
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001247 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001248 status_t ret = NO_ERROR;
1249 String8 id = String8::format("%d", cameraId);
1250 sp<CameraDeviceClient> client = nullptr;
1251 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001252 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001253 /*out*/client);
1254
1255 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001256 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001257 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001259 }
1260
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 device = client;
1262 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001263}
1264
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001265status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1266 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001267
1268 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001269 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001270 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001271 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001272 }
1273
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001274 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001275 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001276
1277 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001278 auto state = getCameraState(id);
1279 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001280 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 return -EINVAL;
1282 }
1283
1284 ICameraServiceListener::Status cameraStatus = state->getStatus();
1285 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1286 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001287 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001288 return -EINVAL;
1289 }
1290
1291 {
1292 Mutex::Autolock al(mTorchStatusMutex);
1293 ICameraServiceListener::TorchStatus status;
1294 status_t res = getTorchStatusLocked(id, &status);
1295 if (res) {
1296 ALOGE("%s: getting current torch status failed for camera %s",
1297 __FUNCTION__, id.string());
1298 return -EINVAL;
1299 }
1300
1301 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001303 ALOGE("%s: torch mode of camera %s is not available because "
1304 "camera is in use", __FUNCTION__, id.string());
1305 return -EBUSY;
1306 } else {
1307 ALOGE("%s: torch mode of camera %s is not available due to "
1308 "insufficient resources", __FUNCTION__, id.string());
1309 return -EUSERS;
1310 }
1311 }
1312 }
1313
Ruben Brunk99e69712015-05-26 17:25:07 -07001314 {
1315 // Update UID map - this is used in the torch status changed callbacks, so must be done
1316 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001317 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001318 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1319 mTorchUidMap[id].first = uid;
1320 mTorchUidMap[id].second = uid;
1321 } else {
1322 // Set the pending UID
1323 mTorchUidMap[id].first = uid;
1324 }
1325 }
1326
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001327 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001328
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001329 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001330 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1331 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001332 return res;
1333 }
1334
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001335 {
1336 // update the link to client's death
1337 Mutex::Autolock al(mTorchClientMapMutex);
1338 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001339 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001340 if (enabled) {
1341 if (index == NAME_NOT_FOUND) {
1342 mTorchClientMap.add(id, clientBinder);
1343 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001344 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001345 mTorchClientMap.replaceValueAt(index, clientBinder);
1346 }
1347 clientBinder->linkToDeath(this);
1348 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001349 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001350 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001351 }
1352
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001353 return OK;
1354}
1355
Ruben Brunk6267b532015-04-30 17:44:07 -07001356void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001357 ATRACE_CALL();
1358
Ruben Brunk36597b22015-03-20 22:15:57 -07001359 switch(eventId) {
1360 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001361 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001362 break;
1363 }
1364 case ICameraService::NO_EVENT:
1365 default: {
1366 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1367 eventId);
1368 break;
1369 }
1370 }
1371}
1372
Ruben Brunk99e69712015-05-26 17:25:07 -07001373status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001374 ATRACE_CALL();
1375
Igor Murashkinbfc99152013-02-27 12:55:20 -08001376 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001377
Ruben Brunk3450ba72015-06-16 11:00:37 -07001378 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001379 ALOGE("%s: Listener must not be null", __FUNCTION__);
1380 return BAD_VALUE;
1381 }
1382
Igor Murashkinbfc99152013-02-27 12:55:20 -08001383 Mutex::Autolock lock(mServiceLock);
1384
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 {
1386 Mutex::Autolock lock(mStatusListenerLock);
1387 for (auto& it : mListenerList) {
1388 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1389 ALOGW("%s: Tried to add listener %p which was already subscribed",
1390 __FUNCTION__, listener.get());
1391 return ALREADY_EXISTS;
1392 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001393 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001394
1395 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001396 }
1397
Igor Murashkinbfc99152013-02-27 12:55:20 -08001398
Igor Murashkincba2c162013-03-20 15:56:31 -07001399 /* Immediately signal current status to this listener only */
1400 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001401 Mutex::Autolock lock(mCameraStatesLock);
1402 for (auto& i : mCameraStates) {
1403 // TODO: Update binder to use String16 for camera IDs and remove;
1404 int id = cameraIdToInt(i.first);
1405 if (id == -1) continue;
1406
1407 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001408 }
1409 }
1410
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001411 /* Immediately signal current torch status to this listener only */
1412 {
1413 Mutex::Autolock al(mTorchStatusMutex);
1414 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001415 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1416 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001417 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001418 }
1419
Igor Murashkinbfc99152013-02-27 12:55:20 -08001420 return OK;
1421}
Ruben Brunkcc776712015-02-17 20:18:47 -08001422
1423status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001424 ATRACE_CALL();
1425
Igor Murashkinbfc99152013-02-27 12:55:20 -08001426 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1427
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001428 if (listener == 0) {
1429 ALOGE("%s: Listener must not be null", __FUNCTION__);
1430 return BAD_VALUE;
1431 }
1432
Igor Murashkinbfc99152013-02-27 12:55:20 -08001433 Mutex::Autolock lock(mServiceLock);
1434
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 {
1436 Mutex::Autolock lock(mStatusListenerLock);
1437 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1438 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1439 mListenerList.erase(it);
1440 return OK;
1441 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001442 }
1443 }
1444
1445 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1446 __FUNCTION__, listener.get());
1447
1448 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001449}
1450
Ruben Brunkcc776712015-02-17 20:18:47 -08001451status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001452
1453 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001454 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1455
1456 if (parameters == NULL) {
1457 ALOGE("%s: parameters must not be null", __FUNCTION__);
1458 return BAD_VALUE;
1459 }
1460
1461 status_t ret = 0;
1462
1463 CameraParameters shimParams;
1464 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1465 // Error logged by caller
1466 return ret;
1467 }
1468
1469 String8 shimParamsString8 = shimParams.flatten();
1470 String16 shimParamsString16 = String16(shimParamsString8);
1471
1472 *parameters = shimParamsString16;
1473
1474 return OK;
1475}
1476
1477status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001478 ATRACE_CALL();
1479
Igor Murashkin65d14b92014-06-17 12:03:20 -07001480 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1481
1482 switch (apiVersion) {
1483 case API_VERSION_1:
1484 case API_VERSION_2:
1485 break;
1486 default:
1487 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1488 return BAD_VALUE;
1489 }
1490
1491 int facing = -1;
1492 int deviceVersion = getDeviceVersion(cameraId, &facing);
1493
1494 switch(deviceVersion) {
1495 case CAMERA_DEVICE_API_VERSION_1_0:
1496 case CAMERA_DEVICE_API_VERSION_2_0:
1497 case CAMERA_DEVICE_API_VERSION_2_1:
1498 case CAMERA_DEVICE_API_VERSION_3_0:
1499 case CAMERA_DEVICE_API_VERSION_3_1:
1500 if (apiVersion == API_VERSION_2) {
1501 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1502 __FUNCTION__, cameraId);
1503 return -EOPNOTSUPP;
1504 } else { // if (apiVersion == API_VERSION_1) {
1505 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1506 __FUNCTION__, cameraId);
1507 return OK;
1508 }
1509 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001510 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001511 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1512 __FUNCTION__, cameraId);
1513 return OK;
1514 case -1:
1515 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1516 return BAD_VALUE;
1517 default:
1518 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1519 return INVALID_OPERATION;
1520 }
1521
1522 return OK;
1523}
1524
Ruben Brunkcc776712015-02-17 20:18:47 -08001525void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001526 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001527 for (auto& i : mActiveClientManager.getAll()) {
1528 auto clientSp = i->getValue();
1529 if (clientSp.get() == client) {
1530 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001531 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001532 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001533}
1534
Ruben Brunkcc776712015-02-17 20:18:47 -08001535bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1536 const int callingPid = getCallingPid();
1537 const int servicePid = getpid();
1538 bool ret = false;
1539 {
1540 // Acquire mServiceLock and prevent other clients from connecting
1541 std::unique_ptr<AutoConditionLock> lock =
1542 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001543
Igor Murashkin634a5152013-02-20 17:15:11 -08001544
Ruben Brunkcc776712015-02-17 20:18:47 -08001545 std::vector<sp<BasicClient>> evicted;
1546 for (auto& i : mActiveClientManager.getAll()) {
1547 auto clientSp = i->getValue();
1548 if (clientSp.get() == nullptr) {
1549 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1550 mActiveClientManager.remove(i);
1551 continue;
1552 }
1553 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1554 callingPid == clientSp->getClientPid())) {
1555 mActiveClientManager.remove(i);
1556 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001557
Ruben Brunkcc776712015-02-17 20:18:47 -08001558 // Notify the client of disconnection
1559 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1560 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001561 }
1562 }
1563
Ruben Brunkcc776712015-02-17 20:18:47 -08001564 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1565 // other clients from connecting in mServiceLockWrapper if held
1566 mServiceLock.unlock();
1567
Ruben Brunk36597b22015-03-20 22:15:57 -07001568 // Do not clear caller identity, remote caller should be client proccess
1569
Ruben Brunkcc776712015-02-17 20:18:47 -08001570 for (auto& i : evicted) {
1571 if (i.get() != nullptr) {
1572 i->disconnect();
1573 ret = true;
1574 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001575 }
1576
Ruben Brunkcc776712015-02-17 20:18:47 -08001577 // Reacquire mServiceLock
1578 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001579
Ruben Brunkcc776712015-02-17 20:18:47 -08001580 } // lock is destroyed, allow further connect calls
1581
1582 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001583}
1584
Igor Murashkinecf17e82012-10-02 16:05:11 -07001585
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001586/**
1587 * Check camera capabilities, such as support for basic color operation
1588 */
1589int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1590
1591 // Assume all devices pre-v3.3 are backward-compatible
1592 bool isBackwardCompatible = true;
1593 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1594 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1595 isBackwardCompatible = false;
1596 status_t res;
1597 camera_metadata_ro_entry_t caps;
1598 res = find_camera_metadata_ro_entry(
1599 info.static_camera_characteristics,
1600 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1601 &caps);
1602 if (res != 0) {
1603 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1604 __FUNCTION__, id);
1605 caps.count = 0;
1606 }
1607 for (size_t i = 0; i < caps.count; i++) {
1608 if (caps.data.u8[i] ==
1609 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1610 isBackwardCompatible = true;
1611 break;
1612 }
1613 }
1614 }
1615
1616 if (!isBackwardCompatible) {
1617 mNumberOfNormalCameras--;
1618 *latestStrangeCameraId = id;
1619 } else {
1620 if (id > *latestStrangeCameraId) {
1621 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1622 "This is not allowed due backward-compatibility requirements",
1623 __FUNCTION__, id, *latestStrangeCameraId);
1624 logServiceError("Invalid order of camera devices", ENODEV);
1625 mNumberOfCameras = 0;
1626 mNumberOfNormalCameras = 0;
1627 return INVALID_OPERATION;
1628 }
1629 }
1630 return OK;
1631}
1632
Ruben Brunkcc776712015-02-17 20:18:47 -08001633std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1634 const String8& cameraId) const {
1635 std::shared_ptr<CameraState> state;
1636 {
1637 Mutex::Autolock lock(mCameraStatesLock);
1638 auto iter = mCameraStates.find(cameraId);
1639 if (iter != mCameraStates.end()) {
1640 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 }
1642 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001643 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644}
1645
Ruben Brunkcc776712015-02-17 20:18:47 -08001646sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1647 // Remove from active clients list
1648 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1649 if (clientDescriptorPtr == nullptr) {
1650 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1651 cameraId.string());
1652 return sp<BasicClient>{nullptr};
1653 }
1654
1655 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001656}
1657
Ruben Brunk6267b532015-04-30 17:44:07 -07001658void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001659 // Acquire mServiceLock and prevent other clients from connecting
1660 std::unique_ptr<AutoConditionLock> lock =
1661 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1662
Ruben Brunk6267b532015-04-30 17:44:07 -07001663 std::set<userid_t> newAllowedUsers;
1664 for (size_t i = 0; i < length; i++) {
1665 if (newUserId[i] < 0) {
1666 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1667 __FUNCTION__, newUserId[i]);
1668 return;
1669 }
1670 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001671 }
1672
Ruben Brunka8ca9152015-04-07 14:23:40 -07001673
Ruben Brunk6267b532015-04-30 17:44:07 -07001674 if (newAllowedUsers == mAllowedUsers) {
1675 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1676 return;
1677 }
1678
1679 logUserSwitch(mAllowedUsers, newAllowedUsers);
1680
1681 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001682
1683 // Current user has switched, evict all current clients.
1684 std::vector<sp<BasicClient>> evicted;
1685 for (auto& i : mActiveClientManager.getAll()) {
1686 auto clientSp = i->getValue();
1687
1688 if (clientSp.get() == nullptr) {
1689 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1690 continue;
1691 }
1692
Ruben Brunk6267b532015-04-30 17:44:07 -07001693 // Don't evict clients that are still allowed.
1694 uid_t clientUid = clientSp->getClientUid();
1695 userid_t clientUserId = multiuser_get_user_id(clientUid);
1696 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1697 continue;
1698 }
1699
Ruben Brunk36597b22015-03-20 22:15:57 -07001700 evicted.push_back(clientSp);
1701
1702 String8 curTime = getFormattedCurrentTime();
1703
1704 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1705 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001706
Ruben Brunk36597b22015-03-20 22:15:57 -07001707 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001708 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001709 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001710 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1711 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001712
1713 }
1714
1715 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1716 // blocking other clients from connecting in mServiceLockWrapper if held.
1717 mServiceLock.unlock();
1718
1719 // Clear caller identity temporarily so client disconnect PID checks work correctly
1720 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1721
1722 for (auto& i : evicted) {
1723 i->disconnect();
1724 }
1725
1726 IPCThreadState::self()->restoreCallingIdentity(token);
1727
1728 // Reacquire mServiceLock
1729 mServiceLock.lock();
1730}
Ruben Brunkcc776712015-02-17 20:18:47 -08001731
Ruben Brunka8ca9152015-04-07 14:23:40 -07001732void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001733 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001734 Mutex::Autolock l(mLogLock);
1735 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736}
1737
Ruben Brunka8ca9152015-04-07 14:23:40 -07001738void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001739 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001740 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001741 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001742 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001743}
1744
1745void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001746 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001747 // Log the clients evicted
1748 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001749 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001750}
1751
1752void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001753 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001754 // Log the client rejected
1755 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001756 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001757}
1758
Ruben Brunk6267b532015-04-30 17:44:07 -07001759void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1760 const std::set<userid_t>& newUserIds) {
1761 String8 newUsers = toString(newUserIds);
1762 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001763 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001764 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1765 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001766}
1767
1768void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1769 // Log the device removal
1770 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1771}
1772
1773void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1774 // Log the device removal
1775 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1776}
1777
1778void CameraService::logClientDied(int clientPid, const char* reason) {
1779 // Log the device removal
1780 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001781}
1782
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001783void CameraService::logServiceError(const char* msg, int errorCode) {
1784 String8 curTime = getFormattedCurrentTime();
1785 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1786}
1787
Ruben Brunk36597b22015-03-20 22:15:57 -07001788status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1789 uint32_t flags) {
1790
1791 const int pid = getCallingPid();
1792 const int selfPid = getpid();
1793
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794 // Permission checks
1795 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001796 case BnCameraService::CONNECT:
1797 case BnCameraService::CONNECT_DEVICE:
1798 case BnCameraService::CONNECT_LEGACY: {
1799 if (pid != selfPid) {
1800 // we're called from a different process, do the real check
1801 if (!checkCallingPermission(
1802 String16("android.permission.CAMERA"))) {
1803 const int uid = getCallingUid();
1804 ALOGE("Permission Denial: "
1805 "can't use the camera pid=%d, uid=%d", pid, uid);
1806 return PERMISSION_DENIED;
1807 }
1808 }
1809 break;
1810 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001811 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1812 if (pid != selfPid) {
1813 // Ensure we're being called by system_server, or similar process with
1814 // permissions to notify the camera service about system events
1815 if (!checkCallingPermission(
1816 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1817 const int uid = getCallingUid();
1818 ALOGE("Permission Denial: cannot send updates to camera service about system"
1819 " events from pid=%d, uid=%d", pid, uid);
1820 return PERMISSION_DENIED;
1821 }
1822 }
1823 break;
1824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 }
1826
1827 return BnCameraService::onTransact(code, data, reply, flags);
1828}
1829
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830// We share the media players for shutter and recording sound for all clients.
1831// A reference count is kept to determine when we will actually release the
1832// media players.
1833
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001834MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001836 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001837 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 mp->prepare();
1839 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001840 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 return NULL;
1842 }
1843 return mp;
1844}
1845
1846void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001847 ATRACE_CALL();
1848
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 Mutex::Autolock lock(mSoundLock);
1850 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1851 if (mSoundRef++) return;
1852
1853 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001854 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1855 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856}
1857
1858void CameraService::releaseSound() {
1859 Mutex::Autolock lock(mSoundLock);
1860 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1861 if (--mSoundRef) return;
1862
1863 for (int i = 0; i < NUM_SOUNDS; i++) {
1864 if (mSoundPlayer[i] != 0) {
1865 mSoundPlayer[i]->disconnect();
1866 mSoundPlayer[i].clear();
1867 }
1868 }
1869}
1870
1871void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001872 ATRACE_CALL();
1873
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874 LOG1("playSound(%d)", kind);
1875 Mutex::Autolock lock(mSoundLock);
1876 sp<MediaPlayer> player = mSoundPlayer[kind];
1877 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001878 player->seekTo(0);
1879 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880 }
1881}
1882
1883// ----------------------------------------------------------------------------
1884
1885CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001886 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001887 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001888 int cameraId, int cameraFacing,
1889 int clientPid, uid_t clientUid,
1890 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001891 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001892 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001893 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001894 cameraId, cameraFacing,
1895 clientPid, clientUid,
1896 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001897{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001899 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001901 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001904
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001905 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906}
1907
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908// tear down the client
1909CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001910 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001911 mDestructionStarted = true;
1912
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001913 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001914 // unconditionally disconnect. function is idempotent
1915 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916}
1917
Igor Murashkin634a5152013-02-20 17:15:11 -08001918CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001919 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001920 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001921 int cameraId, int cameraFacing,
1922 int clientPid, uid_t clientUid,
1923 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001924 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001925{
1926 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001927 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001928 mCameraId = cameraId;
1929 mCameraFacing = cameraFacing;
1930 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001931 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001932 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001933 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001934 mDestructionStarted = false;
1935}
1936
1937CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001938 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001939 mDestructionStarted = true;
1940}
1941
1942void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001943 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001944 return;
1945 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001946 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001947
1948 mCameraService->removeByClient(this);
1949 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001950 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001951
1952 sp<IBinder> remote = getRemote();
1953 if (remote != nullptr) {
1954 remote->unlinkToDeath(mCameraService);
1955 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001956
1957 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001958 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1959
Igor Murashkincba2c162013-03-20 15:56:31 -07001960 // client shouldn't be able to call into us anymore
1961 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001962}
1963
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08001964status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
1965 // No dumping of clients directly over Binder,
1966 // must go through CameraService::dump
1967 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
1968 IPCThreadState::self()->getCallingUid(), NULL, 0);
1969 return OK;
1970}
1971
Ruben Brunkcc776712015-02-17 20:18:47 -08001972String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001973 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001974}
1975
1976
1977int CameraService::BasicClient::getClientPid() const {
1978 return mClientPid;
1979}
1980
Ruben Brunk6267b532015-04-30 17:44:07 -07001981uid_t CameraService::BasicClient::getClientUid() const {
1982 return mClientUid;
1983}
1984
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001985bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1986 // Defaults to API2.
1987 return level == API_2;
1988}
1989
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001990status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001991 ATRACE_CALL();
1992
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001993 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001994 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001995 mOpsCallback = new OpsCallback(this);
1996
Igor Murashkine6800ce2013-03-04 17:25:57 -08001997 {
1998 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001999 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002000 }
2001
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002002 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002003 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002004 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002005 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002006
Svetoslav28e8ef72015-05-11 19:21:31 -07002007 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002008 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002009 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002010 return PERMISSION_DENIED;
2011 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002012
Svetoslav28e8ef72015-05-11 19:21:31 -07002013 if (res == AppOpsManager::MODE_IGNORED) {
2014 ALOGI("Camera %d: Access for \"%s\" has been restricted",
2015 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002016 // Return the same error as for device policy manager rejection
2017 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002018 }
2019
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002020 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002021
2022 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2023 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002025
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002026 // Transition device state to OPEN
2027 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2028 String8::format("%d", mCameraId));
2029
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002030 return OK;
2031}
2032
2033status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002034 ATRACE_CALL();
2035
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002036 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002037 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002038 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002039 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002040 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002041 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002042
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2044 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002045
Ruben Brunkcc776712015-02-17 20:18:47 -08002046 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002047 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002048 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002049
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002050 // Transition device state to CLOSED
2051 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2052 String8::format("%d", mCameraId));
2053
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002054 // Notify flashlight that a camera device is closed.
2055 mCameraService->mFlashlight->deviceClosed(
2056 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002057 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002058 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002059 if (mOpsCallback != NULL) {
2060 mAppOpsManager.stopWatchingMode(mOpsCallback);
2061 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002062 mOpsCallback.clear();
2063
2064 return OK;
2065}
2066
2067void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002068 ATRACE_CALL();
2069
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002070 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002071 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002072
2073 if (op != AppOpsManager::OP_CAMERA) {
2074 ALOGW("Unexpected app ops notification received: %d", op);
2075 return;
2076 }
2077
2078 int32_t res;
2079 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002080 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002081 ALOGV("checkOp returns: %d, %s ", res,
2082 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2083 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2084 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2085 "UNKNOWN");
2086
2087 if (res != AppOpsManager::MODE_ALLOWED) {
2088 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2089 myName.string());
2090 // Reset the client PID to allow server-initiated disconnect,
2091 // and to prevent further calls by client.
2092 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002093 CaptureResultExtras resultExtras; // a dummy result (invalid)
2094 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002095 disconnect();
2096 }
2097}
2098
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099// ----------------------------------------------------------------------------
2100
Ruben Brunkcc776712015-02-17 20:18:47 -08002101// Provide client strong pointer for callbacks.
2102sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2103 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2104 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2105 if (clientDescriptor != nullptr) {
2106 return sp<Client>{
2107 static_cast<Client*>(clientDescriptor->getValue().get())};
2108 }
2109 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110}
2111
Jianing Weicb0652e2014-03-12 18:29:36 -07002112void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2113 const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002114 if (mRemoteCallback != NULL) {
2115 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2116 } else {
2117 ALOGE("mRemoteCallback is NULL!!");
2118 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002119}
2120
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002121// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002122void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002123 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002124 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002125}
2126
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002127bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2128 return level == API_1;
2129}
2130
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002131CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2132 mClient(client) {
2133}
2134
2135void CameraService::Client::OpsCallback::opChanged(int32_t op,
2136 const String16& packageName) {
2137 sp<BasicClient> client = mClient.promote();
2138 if (client != NULL) {
2139 client->opChanged(op, packageName);
2140 }
2141}
2142
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002144// CameraState
2145// ----------------------------------------------------------------------------
2146
2147CameraService::CameraState::CameraState(const String8& id, int cost,
2148 const std::set<String8>& conflicting) : mId(id),
2149 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2150
2151CameraService::CameraState::~CameraState() {}
2152
2153ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2154 Mutex::Autolock lock(mStatusLock);
2155 return mStatus;
2156}
2157
2158CameraParameters CameraService::CameraState::getShimParams() const {
2159 return mShimParams;
2160}
2161
2162void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2163 mShimParams = params;
2164}
2165
2166int CameraService::CameraState::getCost() const {
2167 return mCost;
2168}
2169
2170std::set<String8> CameraService::CameraState::getConflicting() const {
2171 return mConflicting;
2172}
2173
2174String8 CameraService::CameraState::getId() const {
2175 return mId;
2176}
2177
2178// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002179// ClientEventListener
2180// ----------------------------------------------------------------------------
2181
2182void CameraService::ClientEventListener::onClientAdded(
2183 const resource_policy::ClientDescriptor<String8,
2184 sp<CameraService::BasicClient>>& descriptor) {
2185 auto basicClient = descriptor.getValue();
2186 if (basicClient.get() != nullptr) {
2187 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2188 notifier.noteStartCamera(descriptor.getKey(),
2189 static_cast<int>(basicClient->getClientUid()));
2190 }
2191}
2192
2193void CameraService::ClientEventListener::onClientRemoved(
2194 const resource_policy::ClientDescriptor<String8,
2195 sp<CameraService::BasicClient>>& descriptor) {
2196 auto basicClient = descriptor.getValue();
2197 if (basicClient.get() != nullptr) {
2198 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2199 notifier.noteStopCamera(descriptor.getKey(),
2200 static_cast<int>(basicClient->getClientUid()));
2201 }
2202}
2203
2204
2205// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002206// CameraClientManager
2207// ----------------------------------------------------------------------------
2208
Ruben Brunk99e69712015-05-26 17:25:07 -07002209CameraService::CameraClientManager::CameraClientManager() {
2210 setListener(std::make_shared<ClientEventListener>());
2211}
2212
Ruben Brunkcc776712015-02-17 20:18:47 -08002213CameraService::CameraClientManager::~CameraClientManager() {}
2214
2215sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2216 const String8& id) const {
2217 auto descriptor = get(id);
2218 if (descriptor == nullptr) {
2219 return sp<BasicClient>{nullptr};
2220 }
2221 return descriptor->getValue();
2222}
2223
2224String8 CameraService::CameraClientManager::toString() const {
2225 auto all = getAll();
2226 String8 ret("[");
2227 bool hasAny = false;
2228 for (auto& i : all) {
2229 hasAny = true;
2230 String8 key = i->getKey();
2231 int32_t cost = i->getCost();
2232 int32_t pid = i->getOwnerId();
2233 int32_t priority = i->getPriority();
2234 auto conflicting = i->getConflicting();
2235 auto clientSp = i->getValue();
2236 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002237 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002238 if (clientSp.get() != nullptr) {
2239 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002240 uid_t clientUid = clientSp->getClientUid();
2241 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002242 }
2243 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2244 PRId32 ", ", key.string(), cost, pid, priority);
2245
Ruben Brunk6267b532015-04-30 17:44:07 -07002246 if (clientSp.get() != nullptr) {
2247 ret.appendFormat("User Id: %d, ", clientUserId);
2248 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002249 if (packageName.size() != 0) {
2250 ret.appendFormat("Client Package Name: %s", packageName.string());
2251 }
2252
2253 ret.append(", Conflicting Client Devices: {");
2254 for (auto& j : conflicting) {
2255 ret.appendFormat("%s, ", j.string());
2256 }
2257 ret.append("})");
2258 }
2259 if (hasAny) ret.append("\n");
2260 ret.append("]\n");
2261 return ret;
2262}
2263
2264CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2265 const String8& key, const sp<BasicClient>& value, int32_t cost,
2266 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2267
2268 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2269 key, value, cost, conflictingKeys, priority, ownerId);
2270}
2271
2272CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2273 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2274 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2275 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2276}
2277
2278// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279
2280static const int kDumpLockRetries = 50;
2281static const int kDumpLockSleep = 60000;
2282
2283static bool tryLock(Mutex& mutex)
2284{
2285 bool locked = false;
2286 for (int i = 0; i < kDumpLockRetries; ++i) {
2287 if (mutex.tryLock() == NO_ERROR) {
2288 locked = true;
2289 break;
2290 }
2291 usleep(kDumpLockSleep);
2292 }
2293 return locked;
2294}
2295
2296status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002297 ATRACE_CALL();
2298
Ruben Brunka8ca9152015-04-07 14:23:40 -07002299 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002301 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 "can't dump CameraService from pid=%d, uid=%d\n",
2303 getCallingPid(),
2304 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305 write(fd, result.string(), result.size());
2306 } else {
2307 bool locked = tryLock(mServiceLock);
2308 // failed to lock - CameraService is probably deadlocked
2309 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002310 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002311 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 }
2313
2314 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002315 if (!mModule) {
2316 result = String8::format("No camera module available!\n");
2317 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002318
2319 // Dump event log for error information
2320 dumpEventLog(fd);
2321
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002322 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002323 return NO_ERROR;
2324 }
2325
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002326 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2327 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2328 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2329 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002330 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2331 String8 activeClientString = mActiveClientManager.toString();
2332 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002333 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002334
Ruben Brunkf81648e2014-04-17 16:14:57 -07002335 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2336 if (desc == NULL) {
2337 result.appendFormat("Vendor tags left unimplemented.\n");
2338 } else {
2339 result.appendFormat("Vendor tag definitions:\n");
2340 }
2341
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002342 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002343
2344 if (desc != NULL) {
2345 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2346 }
2347
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002348 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002349
2350 bool stateLocked = tryLock(mCameraStatesLock);
2351 if (!stateLocked) {
2352 result = String8::format("CameraStates in use, may be deadlocked\n");
2353 write(fd, result.string(), result.size());
2354 }
2355
2356 for (auto& state : mCameraStates) {
2357 String8 cameraId = state.first;
2358 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002359 camera_info info;
2360
Ruben Brunkcc776712015-02-17 20:18:47 -08002361 // TODO: Change getCameraInfo + HAL to use String cameraIds
2362 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002363 if (rc != OK) {
2364 result.appendFormat(" Error reading static information!\n");
2365 write(fd, result.string(), result.size());
2366 } else {
2367 result.appendFormat(" Facing: %s\n",
2368 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2369 result.appendFormat(" Orientation: %d\n", info.orientation);
2370 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002371 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002372 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2373 } else {
2374 deviceVersion = info.device_version;
2375 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002376
2377 auto conflicting = state.second->getConflicting();
2378 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2379 result.appendFormat(" Conflicting Devices:");
2380 for (auto& id : conflicting) {
Dimitry Ivanov161c9532016-02-12 14:39:48 -08002381 result.appendFormat(" %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002382 }
2383 if (conflicting.size() == 0) {
2384 result.appendFormat(" NONE");
2385 }
2386 result.appendFormat("\n");
2387
2388 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002389 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2390 result.appendFormat(" Device static metadata:\n");
2391 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002392 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002393 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002394 } else {
2395 write(fd, result.string(), result.size());
2396 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002397
2398 CameraParameters p = state.second->getShimParams();
2399 if (!p.isEmpty()) {
2400 result = String8::format(" Camera1 API shim is using parameters:\n ");
2401 write(fd, result.string(), result.size());
2402 p.dump(fd, args);
2403 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002404 }
2405
Ruben Brunkcc776712015-02-17 20:18:47 -08002406 auto clientDescriptor = mActiveClientManager.get(cameraId);
2407 if (clientDescriptor == nullptr) {
2408 result = String8::format(" Device %s is closed, no client instance\n",
2409 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002410 write(fd, result.string(), result.size());
2411 continue;
2412 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002414 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2415 cameraId.string());
2416 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2417 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2418
2419 auto client = clientDescriptor->getValue();
2420 result.appendFormat("Client package: %s\n",
2421 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002422 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002423
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002424 client->dumpClient(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002426
2427 if (stateLocked) mCameraStatesLock.unlock();
2428
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002430 result = String8::format("\nNo active camera clients yet.\n");
2431 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433
2434 if (locked) mServiceLock.unlock();
2435
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002436 // Dump camera traces if there were any
2437 write(fd, "\n", 1);
2438 camera3::CameraTraces::dump(fd, args);
2439
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 // change logging level
2441 int n = args.size();
2442 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002443 String16 verboseOption("-v");
2444 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445 String8 levelStr(args[i+1]);
2446 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002447 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002449 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 }
2451 }
2452 }
2453 return NO_ERROR;
2454}
2455
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002456void CameraService::dumpEventLog(int fd) {
2457 String8 result = String8("\nPrior client events (most recent at top):\n");
2458
2459 Mutex::Autolock l(mLogLock);
2460 for (const auto& msg : mEventLog) {
2461 result.appendFormat(" %s\n", msg.string());
2462 }
2463
2464 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2465 result.append(" ...\n");
2466 } else if (mEventLog.size() == 0) {
2467 result.append(" [no events yet]\n");
2468 }
2469 result.append("\n");
2470
2471 write(fd, result.string(), result.size());
2472}
2473
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002474void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002475 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002476 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2477 if (mTorchClientMap[i] == who) {
2478 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002479 String8 cameraId = mTorchClientMap.keyAt(i);
2480 status_t res = mFlashlight->setTorchMode(cameraId, false);
2481 if (res) {
2482 ALOGE("%s: torch client died but couldn't turn off torch: "
2483 "%s (%d)", __FUNCTION__, strerror(-res), res);
2484 return;
2485 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002486 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002487 break;
2488 }
2489 }
2490}
2491
Ruben Brunkcc776712015-02-17 20:18:47 -08002492/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002493
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002494 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002495 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2496 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002497 */
2498
Ruben Brunka8ca9152015-04-07 14:23:40 -07002499 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2500
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002501 // check torch client
2502 handleTorchClientBinderDied(who);
2503
2504 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002505 if(!evictClientIdByRemote(who)) {
2506 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002507 return;
2508 }
2509
Ruben Brunkcc776712015-02-17 20:18:47 -08002510 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2511 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002512}
2513
Ruben Brunkcc776712015-02-17 20:18:47 -08002514void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2515 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002516}
2517
Ruben Brunkcc776712015-02-17 20:18:47 -08002518void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2519 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2520 // Do not lock mServiceLock here or can get into a deadlock from
2521 // connect() -> disconnect -> updateStatus
2522
2523 auto state = getCameraState(cameraId);
2524
2525 if (state == nullptr) {
2526 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2527 cameraId.string());
2528 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002529 }
2530
Ruben Brunkcc776712015-02-17 20:18:47 -08002531 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2532 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2533 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2534 (const String8& cameraId, ICameraServiceListener::Status status) {
2535
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002536 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2537 // Update torch status if it has a flash unit.
2538 Mutex::Autolock al(mTorchStatusMutex);
2539 ICameraServiceListener::TorchStatus torchStatus;
2540 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2541 NAME_NOT_FOUND) {
2542 ICameraServiceListener::TorchStatus newTorchStatus =
2543 status == ICameraServiceListener::STATUS_PRESENT ?
2544 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2545 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2546 if (torchStatus != newTorchStatus) {
2547 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2548 }
2549 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002550 }
2551
2552 Mutex::Autolock lock(mStatusListenerLock);
2553
2554 for (auto& listener : mListenerList) {
2555 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2556 int id = cameraIdToInt(cameraId);
2557 if (id != -1) listener->onStatusChanged(status, id);
2558 }
2559 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002560}
2561
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002562void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2563 const String8& cameraId) {
2564 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2565 if (proxyBinder == nullptr) return;
2566 String16 id(cameraId);
2567 proxyBinder->notifyCameraState(id, newState);
2568}
2569
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002570status_t CameraService::getTorchStatusLocked(
2571 const String8& cameraId,
2572 ICameraServiceListener::TorchStatus *status) const {
2573 if (!status) {
2574 return BAD_VALUE;
2575 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002576 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2577 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002578 // invalid camera ID or the camera doesn't have a flash unit
2579 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002580 }
2581
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002582 *status = mTorchStatusMap.valueAt(index);
2583 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002584}
2585
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002586status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002587 ICameraServiceListener::TorchStatus status) {
2588 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2589 if (index == NAME_NOT_FOUND) {
2590 return BAD_VALUE;
2591 }
2592 ICameraServiceListener::TorchStatus& item =
2593 mTorchStatusMap.editValueAt(index);
2594 item = status;
2595
2596 return OK;
2597}
2598
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599}; // namespace android