blob: ee7bf222eb7e48c9dbcd4faf876f35473312f936 [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;
Yin-Chia Yeh0b094272016-04-22 13:24:05 -0700447 // CameraInfo is for android.hardware.Camera which does not
448 // support external camera facing. The closest approximation would be
449 // front camera.
450 if (cameraInfo->orientation == CAMERA_FACING_EXTERNAL) {
451 cameraInfo->orientation = CAMERA_FACING_FRONT;
452 }
Iliyan Malchev8951a972011-04-14 16:55:59 -0700453 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454}
455
Ruben Brunkcc776712015-02-17 20:18:47 -0800456int CameraService::cameraIdToInt(const String8& cameraId) {
457 errno = 0;
458 size_t pos = 0;
459 int ret = stoi(std::string{cameraId.string()}, &pos);
460 if (errno != 0 || pos != cameraId.size()) {
461 return -1;
462 }
463 return ret;
464}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700465
466status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700467 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700468 status_t ret = OK;
469 struct CameraInfo info;
470 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
471 return ret;
472 }
473
474 CameraMetadata shimInfo;
475 int32_t orientation = static_cast<int32_t>(info.orientation);
476 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
477 return ret;
478 }
479
480 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
481 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
482 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
483 return ret;
484 }
485
Igor Murashkin65d14b92014-06-17 12:03:20 -0700486 CameraParameters shimParams;
487 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
488 // Error logged by callee
489 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700490 }
491
492 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700493 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700494 Vector<int32_t> formats;
495 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700496 {
497 shimParams.getSupportedPreviewSizes(/*out*/sizes);
498 shimParams.getSupportedPreviewFormats(/*out*/formats);
499 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700500 }
501
502 // Always include IMPLEMENTATION_DEFINED
503 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
504
505 const size_t INTS_PER_CONFIG = 4;
506
507 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700508 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
509
510 Vector<int32_t> streamConfigs;
511 streamConfigs.setCapacity(streamConfigSize);
512
Ruben Brunkb2119af2014-05-09 19:57:56 -0700513 for (size_t i = 0; i < formats.size(); ++i) {
514 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700515 streamConfigs.add(formats[i]);
516 streamConfigs.add(sizes[j].width);
517 streamConfigs.add(sizes[j].height);
518 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700519 }
520 }
521
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700522 for (size_t i = 0; i < jpegSizes.size(); ++i) {
523 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
524 streamConfigs.add(jpegSizes[i].width);
525 streamConfigs.add(jpegSizes[i].height);
526 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
527 }
528
Ruben Brunkb2119af2014-05-09 19:57:56 -0700529 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700530 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700531 return ret;
532 }
533
534 int64_t fakeMinFrames[0];
535 // TODO: Fixme, don't fake min frame durations.
536 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
537 fakeMinFrames, 0)) != OK) {
538 return ret;
539 }
540
541 int64_t fakeStalls[0];
542 // TODO: Fixme, don't fake stall durations.
543 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
544 fakeStalls, 0)) != OK) {
545 return ret;
546 }
547
548 *cameraInfo = shimInfo;
549 return OK;
550}
551
Zhijun He2b59be82013-09-25 10:14:30 -0700552status_t CameraService::getCameraCharacteristics(int cameraId,
553 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700554 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700555 if (!cameraInfo) {
556 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
557 return BAD_VALUE;
558 }
559
560 if (!mModule) {
561 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
562 return -ENODEV;
563 }
564
Zhijun He2b59be82013-09-25 10:14:30 -0700565 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
566 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
567 return BAD_VALUE;
568 }
569
570 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700571 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800572 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700573 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
574 /**
575 * Backwards compatibility mode for old HALs:
576 * - Convert CameraInfo into static CameraMetadata properties.
577 * - Retrieve cached CameraParameters for this camera. If none exist,
578 * attempt to open CameraClient and retrieve the CameraParameters.
579 * - Convert cached CameraParameters into static CameraMetadata
580 * properties.
581 */
582 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700583
Ruben Brunkb2119af2014-05-09 19:57:56 -0700584 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
585 return ret;
586 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700587
Ruben Brunkb2119af2014-05-09 19:57:56 -0700588 } else {
589 /**
590 * Normal HAL 2.1+ codepath.
591 */
592 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800593 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700594 *cameraInfo = info.static_camera_characteristics;
595 }
Zhijun He2b59be82013-09-25 10:14:30 -0700596
597 return ret;
598}
599
Ruben Brunkcc776712015-02-17 20:18:47 -0800600int CameraService::getCallingPid() {
601 return IPCThreadState::self()->getCallingPid();
602}
603
604int CameraService::getCallingUid() {
605 return IPCThreadState::self()->getCallingUid();
606}
607
608String8 CameraService::getFormattedCurrentTime() {
609 time_t now = time(nullptr);
610 char formattedTime[64];
611 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
612 return String8(formattedTime);
613}
614
615int CameraService::getCameraPriorityFromProcState(int procState) {
616 // Find the priority for the camera usage based on the process state. Higher priority clients
617 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700618 if (procState < 0) {
619 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
620 procState);
621 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800622 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700623 // Treat sleeping TOP processes the same as regular TOP processes, for
624 // access priority. This is important for lock-screen camera launch scenarios
625 if (procState == PROCESS_STATE_TOP_SLEEPING) {
626 procState = PROCESS_STATE_TOP;
627 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700628 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800629}
630
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800631status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700632 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800633 if (!mModule) {
634 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
635 return -ENODEV;
636 }
637
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800638 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
639 return OK;
640}
641
Igor Murashkin634a5152013-02-20 17:15:11 -0800642int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700643 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800644 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800645 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800646 return -1;
647 }
648
649 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800650 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800651 deviceVersion = info.device_version;
652 } else {
653 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
654 }
655
656 if (facing) {
657 *facing = info.facing;
658 }
659
660 return deviceVersion;
661}
662
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700663status_t CameraService::filterGetInfoErrorCode(status_t err) {
664 switch(err) {
665 case NO_ERROR:
666 case -EINVAL:
667 return err;
668 default:
669 break;
670 }
671 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800672}
673
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800674bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700675 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800676 vendor_tag_ops_t vOps = vendor_tag_ops_t();
677
678 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800679 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800680 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
681 return false;
682 }
683
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800684 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800685
686 // Ensure all vendor operations are present
687 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
688 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
689 vOps.get_tag_type == NULL) {
690 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
691 , __FUNCTION__);
692 return false;
693 }
694
695 // Read all vendor tag definitions into a descriptor
696 sp<VendorTagDescriptor> desc;
697 status_t res;
698 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
699 != OK) {
700 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
701 "received error %s (%d). Camera clients will not be able to use"
702 "vendor tags", __FUNCTION__, strerror(res), res);
703 return false;
704 }
705
706 // Set the global descriptor to use with camera metadata
707 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
708 return true;
709}
710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711status_t CameraService::makeClient(const sp<CameraService>& cameraService,
712 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
713 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
714 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
715 /*out*/sp<BasicClient>* client) {
716
717 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
718 int id = cameraIdToInt(cameraId);
719 if (id == -1) {
720 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
721 cameraId.string());
722 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700723 }
724
Ruben Brunkcc776712015-02-17 20:18:47 -0800725 if (halVersion < 0 || halVersion == deviceVersion) {
726 // Default path: HAL version is unspecified by caller, create CameraClient
727 // based on device version reported by the HAL.
728 switch(deviceVersion) {
729 case CAMERA_DEVICE_API_VERSION_1_0:
730 if (effectiveApiLevel == API_1) { // Camera1 API route
731 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
732 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
733 clientPid, clientUid, getpid(), legacyMode);
734 } else { // Camera2 API route
735 ALOGW("Camera using old HAL version: %d", deviceVersion);
736 return -EOPNOTSUPP;
737 }
738 break;
739 case CAMERA_DEVICE_API_VERSION_2_0:
740 case CAMERA_DEVICE_API_VERSION_2_1:
741 case CAMERA_DEVICE_API_VERSION_3_0:
742 case CAMERA_DEVICE_API_VERSION_3_1:
743 case CAMERA_DEVICE_API_VERSION_3_2:
744 case CAMERA_DEVICE_API_VERSION_3_3:
745 if (effectiveApiLevel == API_1) { // Camera1 API route
746 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
747 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
748 clientPid, clientUid, servicePid, legacyMode);
749 } else { // Camera2 API route
750 sp<ICameraDeviceCallbacks> tmp =
751 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
752 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
753 facing, clientPid, clientUid, servicePid);
754 }
755 break;
756 default:
757 // Should not be reachable
758 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
759 return INVALID_OPERATION;
760 }
761 } else {
762 // A particular HAL version is requested by caller. Create CameraClient
763 // based on the requested HAL version.
764 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
765 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
766 // Only support higher HAL version device opened as HAL1.0 device.
767 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
768 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
769 clientPid, clientUid, servicePid, legacyMode);
770 } else {
771 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
772 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
773 " opened as HAL %x device", halVersion, deviceVersion,
774 CAMERA_DEVICE_API_VERSION_1_0);
775 return INVALID_OPERATION;
776 }
777 }
778 return NO_ERROR;
779}
780
Ruben Brunk6267b532015-04-30 17:44:07 -0700781String8 CameraService::toString(std::set<userid_t> intSet) {
782 String8 s("");
783 bool first = true;
784 for (userid_t i : intSet) {
785 if (first) {
786 s.appendFormat("%d", i);
787 first = false;
788 } else {
789 s.appendFormat(", %d", i);
790 }
791 }
792 return s;
793}
794
Ruben Brunkcc776712015-02-17 20:18:47 -0800795status_t CameraService::initializeShimMetadata(int cameraId) {
796 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700797
798 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800799 String8 id = String8::format("%d", cameraId);
800 status_t ret = NO_ERROR;
801 sp<Client> tmp = nullptr;
802 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
803 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
804 false, true, tmp)) != NO_ERROR) {
805 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
806 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700807 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800808 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700809}
810
Igor Murashkin65d14b92014-06-17 12:03:20 -0700811status_t CameraService::getLegacyParametersLazy(int cameraId,
812 /*out*/
813 CameraParameters* parameters) {
814
815 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
816
817 status_t ret = 0;
818
819 if (parameters == NULL) {
820 ALOGE("%s: parameters must not be null", __FUNCTION__);
821 return BAD_VALUE;
822 }
823
Ruben Brunkcc776712015-02-17 20:18:47 -0800824 String8 id = String8::format("%d", cameraId);
825
826 // Check if we already have parameters
827 {
828 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700829 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 auto cameraState = getCameraState(id);
831 if (cameraState == nullptr) {
832 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
833 return BAD_VALUE;
834 }
835 CameraParameters p = cameraState->getShimParams();
836 if (!p.isEmpty()) {
837 *parameters = p;
838 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700839 }
840 }
841
Ruben Brunkcc776712015-02-17 20:18:47 -0800842 int64_t token = IPCThreadState::self()->clearCallingIdentity();
843 ret = initializeShimMetadata(cameraId);
844 IPCThreadState::self()->restoreCallingIdentity(token);
845 if (ret != NO_ERROR) {
846 // Error already logged by callee
847 return ret;
848 }
849
850 // Check for parameters again
851 {
852 // Scope for service lock
853 Mutex::Autolock lock(mServiceLock);
854 auto cameraState = getCameraState(id);
855 if (cameraState == nullptr) {
856 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
857 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700858 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800859 CameraParameters p = cameraState->getShimParams();
860 if (!p.isEmpty()) {
861 *parameters = p;
862 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700863 }
864 }
865
Ruben Brunkcc776712015-02-17 20:18:47 -0800866 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
867 __FUNCTION__);
868 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700869}
870
Ruben Brunk36597b22015-03-20 22:15:57 -0700871status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
872 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800873
Mathias Agopian65ab4712010-07-14 17:59:35 -0700874 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500875
Iliyan Malchev8951a972011-04-14 16:55:59 -0700876 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800877 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
878 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700879 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700880 }
881
Ruben Brunkcc776712015-02-17 20:18:47 -0800882 if (getCameraState(cameraId) == nullptr) {
883 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
884 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700885 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700886 }
887
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800888#if !defined(__BRILLO__)
889 status_t allowed = validateClientPermissionsLocked(cameraId, clientUid);
890 if (allowed != OK) {
891 return allowed;
892 }
893#endif // defined(__BRILLO__)
894
895 return checkIfDeviceIsUsable(cameraId);
896}
897
898status_t CameraService::validateClientPermissionsLocked(const String8& cameraId, int& clientUid)
899 const {
900 int callingPid = getCallingPid();
901
902 if (clientUid == USE_CALLING_UID) {
903 clientUid = getCallingUid();
904 } else {
905 // We only trust our own process to forward client UIDs
906 if (callingPid != getpid()) {
907 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
908 callingPid, clientUid);
909 return PERMISSION_DENIED;
910 }
911 }
912
Ruben Brunkcc776712015-02-17 20:18:47 -0800913 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800914 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800915 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700916 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800917 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
918 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800919 if (strcmp(value, "1") == 0) {
920 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800921 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
922 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700923 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800924 }
925
Ruben Brunka8ca9152015-04-07 14:23:40 -0700926 // Only allow clients who are being used by the current foreground device user, unless calling
927 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700928 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
929 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
930 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
931 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700932 return PERMISSION_DENIED;
933 }
934
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800935 return OK;
Ruben Brunkcc776712015-02-17 20:18:47 -0800936}
937
938status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
939 auto cameraState = getCameraState(cameraId);
940 int callingPid = getCallingPid();
941 if (cameraState == nullptr) {
942 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
943 cameraId.string());
944 return -ENODEV;
945 }
946
947 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700948 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
950 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700951 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700952 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800953 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
954 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700955 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700956 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700957
Ruben Brunkcc776712015-02-17 20:18:47 -0800958 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800959}
960
Ruben Brunkcc776712015-02-17 20:18:47 -0800961void CameraService::finishConnectLocked(const sp<BasicClient>& client,
962 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800963
Ruben Brunkcc776712015-02-17 20:18:47 -0800964 // Make a descriptor for the incoming client
965 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
966 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
967
968 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
969 String8(client->getPackageName()));
970
971 if (evicted.size() > 0) {
972 // This should never happen - clients should already have been removed in disconnect
973 for (auto& i : evicted) {
974 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
975 __FUNCTION__, i->getKey().string());
976 }
977
978 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
979 __FUNCTION__);
980 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700981
982 // And register a death notification for the client callback. Do
983 // this last to avoid Binder policy where a nested Binder
984 // transaction might be pre-empted to service the client death
985 // notification if the client process dies before linkToDeath is
986 // invoked.
987 sp<IBinder> remoteCallback = client->getRemote();
988 if (remoteCallback != nullptr) {
989 remoteCallback->linkToDeath(this);
990 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800991}
992
993status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
994 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
995 /*out*/
996 sp<BasicClient>* client,
997 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700998 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800999 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001000 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001001 DescriptorPtr clientDescriptor;
1002 {
1003 if (effectiveApiLevel == API_1) {
1004 // If we are using API1, any existing client for this camera ID with the same remote
1005 // should be returned rather than evicted to allow MediaRecorder to work properly.
1006
1007 auto current = mActiveClientManager.get(cameraId);
1008 if (current != nullptr) {
1009 auto clientSp = current->getValue();
1010 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001011 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1012 ALOGW("CameraService connect called from same client, but with a different"
1013 " API level, evicting prior client...");
1014 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001015 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001016 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 *client = clientSp;
1018 return NO_ERROR;
1019 }
1020 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001021 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001022 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001023
Ruben Brunkcc776712015-02-17 20:18:47 -08001024 // Return error if the device was unplugged or removed by the HAL for some reason
1025 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1026 return ret;
1027 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001028
Ruben Brunkcc776712015-02-17 20:18:47 -08001029 // Get current active client PIDs
1030 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1031 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001032
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001033 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1034 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1035 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1036 // not have an out-of-class definition.
1037 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001038
Ruben Brunkcc776712015-02-17 20:18:47 -08001039 // Get priorites of all active PIDs
1040 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1041 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001042
Ruben Brunkcc776712015-02-17 20:18:47 -08001043 // Update all active clients' priorities
1044 std::map<int,int> pidToPriorityMap;
1045 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1046 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1047 }
1048 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001049
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 // Get state for the given cameraId
1051 auto state = getCameraState(cameraId);
1052 if (state == nullptr) {
1053 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1054 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001055 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001056 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001057
1058 // Make descriptor for incoming client
1059 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1060 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1061 state->getConflicting(),
1062 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1063
1064 // Find clients that would be evicted
1065 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1066
1067 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1068 // background, so we cannot do evictions
1069 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1070 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1071 " priority).", clientPid);
1072
1073 sp<BasicClient> clientSp = clientDescriptor->getValue();
1074 String8 curTime = getFormattedCurrentTime();
1075 auto incompatibleClients =
1076 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1077
1078 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001079 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001080 cameraId.string(), packageName.string(), clientPid,
1081 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1082
1083 for (auto& i : incompatibleClients) {
1084 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1085 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1086 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1087 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001088 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1089 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1090 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1091 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001092 }
1093
1094 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001095 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001096 mEventLog.add(msg);
1097
1098 return -EBUSY;
1099 }
1100
1101 for (auto& i : evicted) {
1102 sp<BasicClient> clientSp = i->getValue();
1103 if (clientSp.get() == nullptr) {
1104 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1105
1106 // TODO: Remove this
1107 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1108 __FUNCTION__);
1109 mActiveClientManager.remove(i);
1110 continue;
1111 }
1112
1113 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1114 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001115 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001116
Ruben Brunkcc776712015-02-17 20:18:47 -08001117 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001118 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1119 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1120 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001121 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1122 i->getOwnerId(), i->getPriority(), cameraId.string(),
1123 packageName.string(), clientPid,
1124 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1125
1126 // Notify the client of disconnection
1127 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1128 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001129 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001130 }
1131
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1133 // other clients from connecting in mServiceLockWrapper if held
1134 mServiceLock.unlock();
1135
1136 // Clear caller identity temporarily so client disconnect PID checks work correctly
1137 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1138
1139 // Destroy evicted clients
1140 for (auto& i : evictedClients) {
1141 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001142 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001144
1145 IPCThreadState::self()->restoreCallingIdentity(token);
1146
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001147 for (const auto& i : evictedClients) {
1148 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1149 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1150 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1151 if (ret == TIMED_OUT) {
1152 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1153 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1154 mActiveClientManager.toString().string());
1155 return -EBUSY;
1156 }
1157 if (ret != NO_ERROR) {
1158 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1159 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1160 ret, mActiveClientManager.toString().string());
1161 return ret;
1162 }
1163 }
1164
1165 evictedClients.clear();
1166
Ruben Brunkcc776712015-02-17 20:18:47 -08001167 // Once clients have been disconnected, relock
1168 mServiceLock.lock();
1169
1170 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1171 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1172 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001173 }
1174
Ruben Brunkcc776712015-02-17 20:18:47 -08001175 *partial = clientDescriptor;
1176 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001177}
1178
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001179status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001180 const sp<ICameraClient>& cameraClient,
1181 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001182 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001183 int clientUid,
1184 /*out*/
1185 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001186
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001187 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001188 status_t ret = NO_ERROR;
1189 String8 id = String8::format("%d", cameraId);
1190 sp<Client> client = nullptr;
1191 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001192 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001193
Ruben Brunkcc776712015-02-17 20:18:47 -08001194 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001195 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001196 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001197 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 }
1199
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001200 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001201 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001202}
1203
Zhijun Heb10cdad2014-06-16 16:38:35 -07001204status_t CameraService::connectLegacy(
1205 const sp<ICameraClient>& cameraClient,
1206 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001207 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001208 int clientUid,
1209 /*out*/
1210 sp<ICamera>& device) {
1211
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001212 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001213 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001214 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001215 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001216 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001217 /*
1218 * Either the HAL version is unspecified in which case this just creates
1219 * a camera client selected by the latest device version, or
1220 * it's a particular version in which case the HAL must supported
1221 * the open_legacy call
1222 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001223 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001224 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001225 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001226 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001227 return INVALID_OPERATION;
1228 }
1229
Ruben Brunkcc776712015-02-17 20:18:47 -08001230 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001231 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001232 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001234
Ruben Brunkcc776712015-02-17 20:18:47 -08001235 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001236 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001237 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001238 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001239 }
1240
Zhijun Heb10cdad2014-06-16 16:38:35 -07001241 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001243}
1244
Ruben Brunkcc776712015-02-17 20:18:47 -08001245status_t CameraService::connectDevice(
1246 const sp<ICameraDeviceCallbacks>& cameraCb,
1247 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001248 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 int clientUid,
1250 /*out*/
1251 sp<ICameraDeviceUser>& device) {
1252
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001253 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001254 status_t ret = NO_ERROR;
1255 String8 id = String8::format("%d", cameraId);
1256 sp<CameraDeviceClient> client = nullptr;
1257 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001258 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001259 /*out*/client);
1260
1261 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001262 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001263 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001264 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001265 }
1266
Ruben Brunkcc776712015-02-17 20:18:47 -08001267 device = client;
1268 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001269}
1270
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001271status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1272 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001273
1274 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001275 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001276 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001277 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001278 }
1279
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001280 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001281 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001282
1283 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001284 auto state = getCameraState(id);
1285 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001286 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001287 return -EINVAL;
1288 }
1289
1290 ICameraServiceListener::Status cameraStatus = state->getStatus();
1291 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1292 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001293 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001294 return -EINVAL;
1295 }
1296
1297 {
1298 Mutex::Autolock al(mTorchStatusMutex);
1299 ICameraServiceListener::TorchStatus status;
1300 status_t res = getTorchStatusLocked(id, &status);
1301 if (res) {
1302 ALOGE("%s: getting current torch status failed for camera %s",
1303 __FUNCTION__, id.string());
1304 return -EINVAL;
1305 }
1306
1307 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001308 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001309 ALOGE("%s: torch mode of camera %s is not available because "
1310 "camera is in use", __FUNCTION__, id.string());
1311 return -EBUSY;
1312 } else {
1313 ALOGE("%s: torch mode of camera %s is not available due to "
1314 "insufficient resources", __FUNCTION__, id.string());
1315 return -EUSERS;
1316 }
1317 }
1318 }
1319
Ruben Brunk99e69712015-05-26 17:25:07 -07001320 {
1321 // Update UID map - this is used in the torch status changed callbacks, so must be done
1322 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001323 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001324 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1325 mTorchUidMap[id].first = uid;
1326 mTorchUidMap[id].second = uid;
1327 } else {
1328 // Set the pending UID
1329 mTorchUidMap[id].first = uid;
1330 }
1331 }
1332
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001333 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001334
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001335 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001336 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1337 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001338 return res;
1339 }
1340
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001341 {
1342 // update the link to client's death
1343 Mutex::Autolock al(mTorchClientMapMutex);
1344 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001345 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001346 if (enabled) {
1347 if (index == NAME_NOT_FOUND) {
1348 mTorchClientMap.add(id, clientBinder);
1349 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001350 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001351 mTorchClientMap.replaceValueAt(index, clientBinder);
1352 }
1353 clientBinder->linkToDeath(this);
1354 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001355 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001356 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001357 }
1358
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001359 return OK;
1360}
1361
Ruben Brunk6267b532015-04-30 17:44:07 -07001362void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001363 ATRACE_CALL();
1364
Ruben Brunk36597b22015-03-20 22:15:57 -07001365 switch(eventId) {
1366 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001367 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001368 break;
1369 }
1370 case ICameraService::NO_EVENT:
1371 default: {
1372 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1373 eventId);
1374 break;
1375 }
1376 }
1377}
1378
Ruben Brunk99e69712015-05-26 17:25:07 -07001379status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001380 ATRACE_CALL();
1381
Igor Murashkinbfc99152013-02-27 12:55:20 -08001382 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001383
Ruben Brunk3450ba72015-06-16 11:00:37 -07001384 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001385 ALOGE("%s: Listener must not be null", __FUNCTION__);
1386 return BAD_VALUE;
1387 }
1388
Igor Murashkinbfc99152013-02-27 12:55:20 -08001389 Mutex::Autolock lock(mServiceLock);
1390
Ruben Brunkcc776712015-02-17 20:18:47 -08001391 {
1392 Mutex::Autolock lock(mStatusListenerLock);
1393 for (auto& it : mListenerList) {
1394 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1395 ALOGW("%s: Tried to add listener %p which was already subscribed",
1396 __FUNCTION__, listener.get());
1397 return ALREADY_EXISTS;
1398 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001399 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001400
1401 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001402 }
1403
Igor Murashkinbfc99152013-02-27 12:55:20 -08001404
Igor Murashkincba2c162013-03-20 15:56:31 -07001405 /* Immediately signal current status to this listener only */
1406 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001407 Mutex::Autolock lock(mCameraStatesLock);
1408 for (auto& i : mCameraStates) {
1409 // TODO: Update binder to use String16 for camera IDs and remove;
1410 int id = cameraIdToInt(i.first);
1411 if (id == -1) continue;
1412
1413 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001414 }
1415 }
1416
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001417 /* Immediately signal current torch status to this listener only */
1418 {
1419 Mutex::Autolock al(mTorchStatusMutex);
1420 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001421 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1422 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001423 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001424 }
1425
Igor Murashkinbfc99152013-02-27 12:55:20 -08001426 return OK;
1427}
Ruben Brunkcc776712015-02-17 20:18:47 -08001428
1429status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001430 ATRACE_CALL();
1431
Igor Murashkinbfc99152013-02-27 12:55:20 -08001432 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1433
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001434 if (listener == 0) {
1435 ALOGE("%s: Listener must not be null", __FUNCTION__);
1436 return BAD_VALUE;
1437 }
1438
Igor Murashkinbfc99152013-02-27 12:55:20 -08001439 Mutex::Autolock lock(mServiceLock);
1440
Ruben Brunkcc776712015-02-17 20:18:47 -08001441 {
1442 Mutex::Autolock lock(mStatusListenerLock);
1443 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1444 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1445 mListenerList.erase(it);
1446 return OK;
1447 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001448 }
1449 }
1450
1451 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1452 __FUNCTION__, listener.get());
1453
1454 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001455}
1456
Ruben Brunkcc776712015-02-17 20:18:47 -08001457status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001458
1459 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001460 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1461
1462 if (parameters == NULL) {
1463 ALOGE("%s: parameters must not be null", __FUNCTION__);
1464 return BAD_VALUE;
1465 }
1466
1467 status_t ret = 0;
1468
1469 CameraParameters shimParams;
1470 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1471 // Error logged by caller
1472 return ret;
1473 }
1474
1475 String8 shimParamsString8 = shimParams.flatten();
1476 String16 shimParamsString16 = String16(shimParamsString8);
1477
1478 *parameters = shimParamsString16;
1479
1480 return OK;
1481}
1482
1483status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001484 ATRACE_CALL();
1485
Igor Murashkin65d14b92014-06-17 12:03:20 -07001486 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1487
1488 switch (apiVersion) {
1489 case API_VERSION_1:
1490 case API_VERSION_2:
1491 break;
1492 default:
1493 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1494 return BAD_VALUE;
1495 }
1496
1497 int facing = -1;
1498 int deviceVersion = getDeviceVersion(cameraId, &facing);
1499
1500 switch(deviceVersion) {
1501 case CAMERA_DEVICE_API_VERSION_1_0:
1502 case CAMERA_DEVICE_API_VERSION_2_0:
1503 case CAMERA_DEVICE_API_VERSION_2_1:
1504 case CAMERA_DEVICE_API_VERSION_3_0:
1505 case CAMERA_DEVICE_API_VERSION_3_1:
1506 if (apiVersion == API_VERSION_2) {
1507 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1508 __FUNCTION__, cameraId);
1509 return -EOPNOTSUPP;
1510 } else { // if (apiVersion == API_VERSION_1) {
1511 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1512 __FUNCTION__, cameraId);
1513 return OK;
1514 }
1515 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001516 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001517 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1518 __FUNCTION__, cameraId);
1519 return OK;
1520 case -1:
1521 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1522 return BAD_VALUE;
1523 default:
1524 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1525 return INVALID_OPERATION;
1526 }
1527
1528 return OK;
1529}
1530
Ruben Brunkcc776712015-02-17 20:18:47 -08001531void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001532 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001533 for (auto& i : mActiveClientManager.getAll()) {
1534 auto clientSp = i->getValue();
1535 if (clientSp.get() == client) {
1536 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001537 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001538 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001539}
1540
Ruben Brunkcc776712015-02-17 20:18:47 -08001541bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1542 const int callingPid = getCallingPid();
1543 const int servicePid = getpid();
1544 bool ret = false;
1545 {
1546 // Acquire mServiceLock and prevent other clients from connecting
1547 std::unique_ptr<AutoConditionLock> lock =
1548 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001549
Igor Murashkin634a5152013-02-20 17:15:11 -08001550
Ruben Brunkcc776712015-02-17 20:18:47 -08001551 std::vector<sp<BasicClient>> evicted;
1552 for (auto& i : mActiveClientManager.getAll()) {
1553 auto clientSp = i->getValue();
1554 if (clientSp.get() == nullptr) {
1555 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1556 mActiveClientManager.remove(i);
1557 continue;
1558 }
1559 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1560 callingPid == clientSp->getClientPid())) {
1561 mActiveClientManager.remove(i);
1562 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001563
Ruben Brunkcc776712015-02-17 20:18:47 -08001564 // Notify the client of disconnection
1565 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1566 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001567 }
1568 }
1569
Ruben Brunkcc776712015-02-17 20:18:47 -08001570 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1571 // other clients from connecting in mServiceLockWrapper if held
1572 mServiceLock.unlock();
1573
Ruben Brunk36597b22015-03-20 22:15:57 -07001574 // Do not clear caller identity, remote caller should be client proccess
1575
Ruben Brunkcc776712015-02-17 20:18:47 -08001576 for (auto& i : evicted) {
1577 if (i.get() != nullptr) {
1578 i->disconnect();
1579 ret = true;
1580 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001581 }
1582
Ruben Brunkcc776712015-02-17 20:18:47 -08001583 // Reacquire mServiceLock
1584 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001585
Ruben Brunkcc776712015-02-17 20:18:47 -08001586 } // lock is destroyed, allow further connect calls
1587
1588 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001589}
1590
Igor Murashkinecf17e82012-10-02 16:05:11 -07001591
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001592/**
1593 * Check camera capabilities, such as support for basic color operation
1594 */
1595int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1596
1597 // Assume all devices pre-v3.3 are backward-compatible
1598 bool isBackwardCompatible = true;
1599 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1600 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1601 isBackwardCompatible = false;
1602 status_t res;
1603 camera_metadata_ro_entry_t caps;
1604 res = find_camera_metadata_ro_entry(
1605 info.static_camera_characteristics,
1606 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1607 &caps);
1608 if (res != 0) {
1609 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1610 __FUNCTION__, id);
1611 caps.count = 0;
1612 }
1613 for (size_t i = 0; i < caps.count; i++) {
1614 if (caps.data.u8[i] ==
1615 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1616 isBackwardCompatible = true;
1617 break;
1618 }
1619 }
1620 }
1621
1622 if (!isBackwardCompatible) {
1623 mNumberOfNormalCameras--;
1624 *latestStrangeCameraId = id;
1625 } else {
1626 if (id > *latestStrangeCameraId) {
1627 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1628 "This is not allowed due backward-compatibility requirements",
1629 __FUNCTION__, id, *latestStrangeCameraId);
1630 logServiceError("Invalid order of camera devices", ENODEV);
1631 mNumberOfCameras = 0;
1632 mNumberOfNormalCameras = 0;
1633 return INVALID_OPERATION;
1634 }
1635 }
1636 return OK;
1637}
1638
Ruben Brunkcc776712015-02-17 20:18:47 -08001639std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1640 const String8& cameraId) const {
1641 std::shared_ptr<CameraState> state;
1642 {
1643 Mutex::Autolock lock(mCameraStatesLock);
1644 auto iter = mCameraStates.find(cameraId);
1645 if (iter != mCameraStates.end()) {
1646 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 }
1648 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001649 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650}
1651
Ruben Brunkcc776712015-02-17 20:18:47 -08001652sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1653 // Remove from active clients list
1654 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1655 if (clientDescriptorPtr == nullptr) {
1656 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1657 cameraId.string());
1658 return sp<BasicClient>{nullptr};
1659 }
1660
1661 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001662}
1663
Ruben Brunk6267b532015-04-30 17:44:07 -07001664void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001665 // Acquire mServiceLock and prevent other clients from connecting
1666 std::unique_ptr<AutoConditionLock> lock =
1667 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1668
Ruben Brunk6267b532015-04-30 17:44:07 -07001669 std::set<userid_t> newAllowedUsers;
1670 for (size_t i = 0; i < length; i++) {
1671 if (newUserId[i] < 0) {
1672 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1673 __FUNCTION__, newUserId[i]);
1674 return;
1675 }
1676 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001677 }
1678
Ruben Brunka8ca9152015-04-07 14:23:40 -07001679
Ruben Brunk6267b532015-04-30 17:44:07 -07001680 if (newAllowedUsers == mAllowedUsers) {
1681 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1682 return;
1683 }
1684
1685 logUserSwitch(mAllowedUsers, newAllowedUsers);
1686
1687 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001688
1689 // Current user has switched, evict all current clients.
1690 std::vector<sp<BasicClient>> evicted;
1691 for (auto& i : mActiveClientManager.getAll()) {
1692 auto clientSp = i->getValue();
1693
1694 if (clientSp.get() == nullptr) {
1695 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1696 continue;
1697 }
1698
Ruben Brunk6267b532015-04-30 17:44:07 -07001699 // Don't evict clients that are still allowed.
1700 uid_t clientUid = clientSp->getClientUid();
1701 userid_t clientUserId = multiuser_get_user_id(clientUid);
1702 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1703 continue;
1704 }
1705
Ruben Brunk36597b22015-03-20 22:15:57 -07001706 evicted.push_back(clientSp);
1707
1708 String8 curTime = getFormattedCurrentTime();
1709
1710 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1711 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001712
Ruben Brunk36597b22015-03-20 22:15:57 -07001713 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001714 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001715 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001716 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1717 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001718
1719 }
1720
1721 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1722 // blocking other clients from connecting in mServiceLockWrapper if held.
1723 mServiceLock.unlock();
1724
1725 // Clear caller identity temporarily so client disconnect PID checks work correctly
1726 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1727
1728 for (auto& i : evicted) {
1729 i->disconnect();
1730 }
1731
1732 IPCThreadState::self()->restoreCallingIdentity(token);
1733
1734 // Reacquire mServiceLock
1735 mServiceLock.lock();
1736}
Ruben Brunkcc776712015-02-17 20:18:47 -08001737
Ruben Brunka8ca9152015-04-07 14:23:40 -07001738void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001739 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001740 Mutex::Autolock l(mLogLock);
1741 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742}
1743
Ruben Brunka8ca9152015-04-07 14:23:40 -07001744void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001745 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001746 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001747 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001748 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001749}
1750
1751void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001752 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001753 // Log the clients evicted
1754 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001755 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001756}
1757
1758void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001759 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001760 // Log the client rejected
1761 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001762 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001763}
1764
Ruben Brunk6267b532015-04-30 17:44:07 -07001765void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1766 const std::set<userid_t>& newUserIds) {
1767 String8 newUsers = toString(newUserIds);
1768 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001769 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001770 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1771 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001772}
1773
1774void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1775 // Log the device removal
1776 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1777}
1778
1779void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1780 // Log the device removal
1781 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1782}
1783
1784void CameraService::logClientDied(int clientPid, const char* reason) {
1785 // Log the device removal
1786 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001787}
1788
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001789void CameraService::logServiceError(const char* msg, int errorCode) {
1790 String8 curTime = getFormattedCurrentTime();
1791 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1792}
1793
Ruben Brunk36597b22015-03-20 22:15:57 -07001794status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1795 uint32_t flags) {
1796
1797 const int pid = getCallingPid();
1798 const int selfPid = getpid();
1799
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800 // Permission checks
1801 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001802 case BnCameraService::CONNECT:
1803 case BnCameraService::CONNECT_DEVICE:
1804 case BnCameraService::CONNECT_LEGACY: {
1805 if (pid != selfPid) {
1806 // we're called from a different process, do the real check
1807 if (!checkCallingPermission(
1808 String16("android.permission.CAMERA"))) {
1809 const int uid = getCallingUid();
1810 ALOGE("Permission Denial: "
1811 "can't use the camera pid=%d, uid=%d", pid, uid);
1812 return PERMISSION_DENIED;
1813 }
1814 }
1815 break;
1816 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001817 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1818 if (pid != selfPid) {
1819 // Ensure we're being called by system_server, or similar process with
1820 // permissions to notify the camera service about system events
1821 if (!checkCallingPermission(
1822 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1823 const int uid = getCallingUid();
1824 ALOGE("Permission Denial: cannot send updates to camera service about system"
1825 " events from pid=%d, uid=%d", pid, uid);
1826 return PERMISSION_DENIED;
1827 }
1828 }
1829 break;
1830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 }
1832
1833 return BnCameraService::onTransact(code, data, reply, flags);
1834}
1835
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836// We share the media players for shutter and recording sound for all clients.
1837// A reference count is kept to determine when we will actually release the
1838// media players.
1839
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001840MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001842 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001843 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 mp->prepare();
1845 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001846 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847 return NULL;
1848 }
1849 return mp;
1850}
1851
1852void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001853 ATRACE_CALL();
1854
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 Mutex::Autolock lock(mSoundLock);
1856 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1857 if (mSoundRef++) return;
1858
1859 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001860 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1861 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862}
1863
1864void CameraService::releaseSound() {
1865 Mutex::Autolock lock(mSoundLock);
1866 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1867 if (--mSoundRef) return;
1868
1869 for (int i = 0; i < NUM_SOUNDS; i++) {
1870 if (mSoundPlayer[i] != 0) {
1871 mSoundPlayer[i]->disconnect();
1872 mSoundPlayer[i].clear();
1873 }
1874 }
1875}
1876
1877void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001878 ATRACE_CALL();
1879
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880 LOG1("playSound(%d)", kind);
1881 Mutex::Autolock lock(mSoundLock);
1882 sp<MediaPlayer> player = mSoundPlayer[kind];
1883 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001884 player->seekTo(0);
1885 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886 }
1887}
1888
1889// ----------------------------------------------------------------------------
1890
1891CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001892 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001893 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001894 int cameraId, int cameraFacing,
1895 int clientPid, uid_t clientUid,
1896 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001897 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001898 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001899 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001900 cameraId, cameraFacing,
1901 clientPid, clientUid,
1902 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001903{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001905 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001907 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001910
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001911 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912}
1913
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914// tear down the client
1915CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001916 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001917 mDestructionStarted = true;
1918
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001919 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001920 // unconditionally disconnect. function is idempotent
1921 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922}
1923
Igor Murashkin634a5152013-02-20 17:15:11 -08001924CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001925 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001926 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001927 int cameraId, int cameraFacing,
1928 int clientPid, uid_t clientUid,
1929 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001930 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001931{
1932 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001933 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001934 mCameraId = cameraId;
1935 mCameraFacing = cameraFacing;
1936 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001937 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001938 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001939 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001940 mDestructionStarted = false;
1941}
1942
1943CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001944 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001945 mDestructionStarted = true;
1946}
1947
1948void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001949 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001950 return;
1951 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001952 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001953
1954 mCameraService->removeByClient(this);
1955 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001956 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001957
1958 sp<IBinder> remote = getRemote();
1959 if (remote != nullptr) {
1960 remote->unlinkToDeath(mCameraService);
1961 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001962
1963 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001964 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1965
Igor Murashkincba2c162013-03-20 15:56:31 -07001966 // client shouldn't be able to call into us anymore
1967 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001968}
1969
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08001970status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
1971 // No dumping of clients directly over Binder,
1972 // must go through CameraService::dump
1973 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
1974 IPCThreadState::self()->getCallingUid(), NULL, 0);
1975 return OK;
1976}
1977
Ruben Brunkcc776712015-02-17 20:18:47 -08001978String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001979 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001980}
1981
1982
1983int CameraService::BasicClient::getClientPid() const {
1984 return mClientPid;
1985}
1986
Ruben Brunk6267b532015-04-30 17:44:07 -07001987uid_t CameraService::BasicClient::getClientUid() const {
1988 return mClientUid;
1989}
1990
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001991bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1992 // Defaults to API2.
1993 return level == API_2;
1994}
1995
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001996status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001997 ATRACE_CALL();
1998
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001999 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002000 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002001 mOpsCallback = new OpsCallback(this);
2002
Igor Murashkine6800ce2013-03-04 17:25:57 -08002003 {
2004 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002005 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002006 }
2007
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002008 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002009 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002010 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002011 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002012
Svetoslav28e8ef72015-05-11 19:21:31 -07002013 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002014 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002015 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002016 return PERMISSION_DENIED;
2017 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002018
Svetoslav28e8ef72015-05-11 19:21:31 -07002019 if (res == AppOpsManager::MODE_IGNORED) {
2020 ALOGI("Camera %d: Access for \"%s\" has been restricted",
2021 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002022 // Return the same error as for device policy manager rejection
2023 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002024 }
2025
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002026 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002027
2028 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2029 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002030 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002031
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002032 // Transition device state to OPEN
2033 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2034 String8::format("%d", mCameraId));
2035
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002036 return OK;
2037}
2038
2039status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002040 ATRACE_CALL();
2041
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002042 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002043 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002044 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002045 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002046 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002047 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002048
Ruben Brunkcc776712015-02-17 20:18:47 -08002049 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2050 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002051
Ruben Brunkcc776712015-02-17 20:18:47 -08002052 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002053 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002054 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002055
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002056 // Transition device state to CLOSED
2057 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2058 String8::format("%d", mCameraId));
2059
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002060 // Notify flashlight that a camera device is closed.
2061 mCameraService->mFlashlight->deviceClosed(
2062 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002063 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002064 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002065 if (mOpsCallback != NULL) {
2066 mAppOpsManager.stopWatchingMode(mOpsCallback);
2067 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002068 mOpsCallback.clear();
2069
2070 return OK;
2071}
2072
2073void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002074 ATRACE_CALL();
2075
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002076 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002077 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002078
2079 if (op != AppOpsManager::OP_CAMERA) {
2080 ALOGW("Unexpected app ops notification received: %d", op);
2081 return;
2082 }
2083
2084 int32_t res;
2085 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002086 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002087 ALOGV("checkOp returns: %d, %s ", res,
2088 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2089 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2090 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2091 "UNKNOWN");
2092
2093 if (res != AppOpsManager::MODE_ALLOWED) {
2094 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2095 myName.string());
2096 // Reset the client PID to allow server-initiated disconnect,
2097 // and to prevent further calls by client.
2098 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002099 CaptureResultExtras resultExtras; // a dummy result (invalid)
2100 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002101 disconnect();
2102 }
2103}
2104
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105// ----------------------------------------------------------------------------
2106
Ruben Brunkcc776712015-02-17 20:18:47 -08002107// Provide client strong pointer for callbacks.
2108sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2109 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2110 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2111 if (clientDescriptor != nullptr) {
2112 return sp<Client>{
2113 static_cast<Client*>(clientDescriptor->getValue().get())};
2114 }
2115 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116}
2117
Jianing Weicb0652e2014-03-12 18:29:36 -07002118void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2119 const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002120 if (mRemoteCallback != NULL) {
2121 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2122 } else {
2123 ALOGE("mRemoteCallback is NULL!!");
2124 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002125}
2126
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002127// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002128void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002129 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002130 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002131}
2132
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002133bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2134 return level == API_1;
2135}
2136
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002137CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2138 mClient(client) {
2139}
2140
2141void CameraService::Client::OpsCallback::opChanged(int32_t op,
2142 const String16& packageName) {
2143 sp<BasicClient> client = mClient.promote();
2144 if (client != NULL) {
2145 client->opChanged(op, packageName);
2146 }
2147}
2148
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002150// CameraState
2151// ----------------------------------------------------------------------------
2152
2153CameraService::CameraState::CameraState(const String8& id, int cost,
2154 const std::set<String8>& conflicting) : mId(id),
2155 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2156
2157CameraService::CameraState::~CameraState() {}
2158
2159ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2160 Mutex::Autolock lock(mStatusLock);
2161 return mStatus;
2162}
2163
2164CameraParameters CameraService::CameraState::getShimParams() const {
2165 return mShimParams;
2166}
2167
2168void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2169 mShimParams = params;
2170}
2171
2172int CameraService::CameraState::getCost() const {
2173 return mCost;
2174}
2175
2176std::set<String8> CameraService::CameraState::getConflicting() const {
2177 return mConflicting;
2178}
2179
2180String8 CameraService::CameraState::getId() const {
2181 return mId;
2182}
2183
2184// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002185// ClientEventListener
2186// ----------------------------------------------------------------------------
2187
2188void CameraService::ClientEventListener::onClientAdded(
2189 const resource_policy::ClientDescriptor<String8,
2190 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002191 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002192 if (basicClient.get() != nullptr) {
2193 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2194 notifier.noteStartCamera(descriptor.getKey(),
2195 static_cast<int>(basicClient->getClientUid()));
2196 }
2197}
2198
2199void CameraService::ClientEventListener::onClientRemoved(
2200 const resource_policy::ClientDescriptor<String8,
2201 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002202 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002203 if (basicClient.get() != nullptr) {
2204 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2205 notifier.noteStopCamera(descriptor.getKey(),
2206 static_cast<int>(basicClient->getClientUid()));
2207 }
2208}
2209
2210
2211// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002212// CameraClientManager
2213// ----------------------------------------------------------------------------
2214
Ruben Brunk99e69712015-05-26 17:25:07 -07002215CameraService::CameraClientManager::CameraClientManager() {
2216 setListener(std::make_shared<ClientEventListener>());
2217}
2218
Ruben Brunkcc776712015-02-17 20:18:47 -08002219CameraService::CameraClientManager::~CameraClientManager() {}
2220
2221sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2222 const String8& id) const {
2223 auto descriptor = get(id);
2224 if (descriptor == nullptr) {
2225 return sp<BasicClient>{nullptr};
2226 }
2227 return descriptor->getValue();
2228}
2229
2230String8 CameraService::CameraClientManager::toString() const {
2231 auto all = getAll();
2232 String8 ret("[");
2233 bool hasAny = false;
2234 for (auto& i : all) {
2235 hasAny = true;
2236 String8 key = i->getKey();
2237 int32_t cost = i->getCost();
2238 int32_t pid = i->getOwnerId();
2239 int32_t priority = i->getPriority();
2240 auto conflicting = i->getConflicting();
2241 auto clientSp = i->getValue();
2242 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002243 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002244 if (clientSp.get() != nullptr) {
2245 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002246 uid_t clientUid = clientSp->getClientUid();
2247 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002248 }
2249 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2250 PRId32 ", ", key.string(), cost, pid, priority);
2251
Ruben Brunk6267b532015-04-30 17:44:07 -07002252 if (clientSp.get() != nullptr) {
2253 ret.appendFormat("User Id: %d, ", clientUserId);
2254 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002255 if (packageName.size() != 0) {
2256 ret.appendFormat("Client Package Name: %s", packageName.string());
2257 }
2258
2259 ret.append(", Conflicting Client Devices: {");
2260 for (auto& j : conflicting) {
2261 ret.appendFormat("%s, ", j.string());
2262 }
2263 ret.append("})");
2264 }
2265 if (hasAny) ret.append("\n");
2266 ret.append("]\n");
2267 return ret;
2268}
2269
2270CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2271 const String8& key, const sp<BasicClient>& value, int32_t cost,
2272 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2273
2274 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2275 key, value, cost, conflictingKeys, priority, ownerId);
2276}
2277
2278CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2279 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2280 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2281 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2282}
2283
2284// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002285
2286static const int kDumpLockRetries = 50;
2287static const int kDumpLockSleep = 60000;
2288
2289static bool tryLock(Mutex& mutex)
2290{
2291 bool locked = false;
2292 for (int i = 0; i < kDumpLockRetries; ++i) {
2293 if (mutex.tryLock() == NO_ERROR) {
2294 locked = true;
2295 break;
2296 }
2297 usleep(kDumpLockSleep);
2298 }
2299 return locked;
2300}
2301
2302status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002303 ATRACE_CALL();
2304
Ruben Brunka8ca9152015-04-07 14:23:40 -07002305 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002307 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308 "can't dump CameraService from pid=%d, uid=%d\n",
2309 getCallingPid(),
2310 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311 write(fd, result.string(), result.size());
2312 } else {
2313 bool locked = tryLock(mServiceLock);
2314 // failed to lock - CameraService is probably deadlocked
2315 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002316 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002317 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 }
2319
2320 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002321 if (!mModule) {
2322 result = String8::format("No camera module available!\n");
2323 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002324
2325 // Dump event log for error information
2326 dumpEventLog(fd);
2327
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002328 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002329 return NO_ERROR;
2330 }
2331
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002332 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2333 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2334 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2335 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002336 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2337 String8 activeClientString = mActiveClientManager.toString();
2338 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002339 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002340
Ruben Brunkf81648e2014-04-17 16:14:57 -07002341 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2342 if (desc == NULL) {
2343 result.appendFormat("Vendor tags left unimplemented.\n");
2344 } else {
2345 result.appendFormat("Vendor tag definitions:\n");
2346 }
2347
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002348 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002349
2350 if (desc != NULL) {
2351 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2352 }
2353
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002354 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002355
2356 bool stateLocked = tryLock(mCameraStatesLock);
2357 if (!stateLocked) {
2358 result = String8::format("CameraStates in use, may be deadlocked\n");
2359 write(fd, result.string(), result.size());
2360 }
2361
2362 for (auto& state : mCameraStates) {
2363 String8 cameraId = state.first;
2364 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002365 camera_info info;
2366
Ruben Brunkcc776712015-02-17 20:18:47 -08002367 // TODO: Change getCameraInfo + HAL to use String cameraIds
2368 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002369 if (rc != OK) {
2370 result.appendFormat(" Error reading static information!\n");
2371 write(fd, result.string(), result.size());
2372 } else {
2373 result.appendFormat(" Facing: %s\n",
2374 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2375 result.appendFormat(" Orientation: %d\n", info.orientation);
2376 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002377 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002378 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2379 } else {
2380 deviceVersion = info.device_version;
2381 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002382
2383 auto conflicting = state.second->getConflicting();
2384 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2385 result.appendFormat(" Conflicting Devices:");
2386 for (auto& id : conflicting) {
Dimitry Ivanov161c9532016-02-12 14:39:48 -08002387 result.appendFormat(" %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002388 }
2389 if (conflicting.size() == 0) {
2390 result.appendFormat(" NONE");
2391 }
2392 result.appendFormat("\n");
2393
2394 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002395 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2396 result.appendFormat(" Device static metadata:\n");
2397 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002398 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002399 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002400 } else {
2401 write(fd, result.string(), result.size());
2402 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002403
2404 CameraParameters p = state.second->getShimParams();
2405 if (!p.isEmpty()) {
2406 result = String8::format(" Camera1 API shim is using parameters:\n ");
2407 write(fd, result.string(), result.size());
2408 p.dump(fd, args);
2409 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002410 }
2411
Ruben Brunkcc776712015-02-17 20:18:47 -08002412 auto clientDescriptor = mActiveClientManager.get(cameraId);
2413 if (clientDescriptor == nullptr) {
2414 result = String8::format(" Device %s is closed, no client instance\n",
2415 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002416 write(fd, result.string(), result.size());
2417 continue;
2418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002420 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2421 cameraId.string());
2422 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2423 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2424
2425 auto client = clientDescriptor->getValue();
2426 result.appendFormat("Client package: %s\n",
2427 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002428 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002429
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002430 client->dumpClient(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002432
2433 if (stateLocked) mCameraStatesLock.unlock();
2434
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002436 result = String8::format("\nNo active camera clients yet.\n");
2437 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 }
2439
2440 if (locked) mServiceLock.unlock();
2441
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002442 // Dump camera traces if there were any
2443 write(fd, "\n", 1);
2444 camera3::CameraTraces::dump(fd, args);
2445
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 // change logging level
2447 int n = args.size();
2448 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002449 String16 verboseOption("-v");
2450 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 String8 levelStr(args[i+1]);
2452 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002453 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002455 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 }
2457 }
2458 }
2459 return NO_ERROR;
2460}
2461
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002462void CameraService::dumpEventLog(int fd) {
2463 String8 result = String8("\nPrior client events (most recent at top):\n");
2464
2465 Mutex::Autolock l(mLogLock);
2466 for (const auto& msg : mEventLog) {
2467 result.appendFormat(" %s\n", msg.string());
2468 }
2469
2470 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2471 result.append(" ...\n");
2472 } else if (mEventLog.size() == 0) {
2473 result.append(" [no events yet]\n");
2474 }
2475 result.append("\n");
2476
2477 write(fd, result.string(), result.size());
2478}
2479
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002480void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002481 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002482 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2483 if (mTorchClientMap[i] == who) {
2484 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002485 String8 cameraId = mTorchClientMap.keyAt(i);
2486 status_t res = mFlashlight->setTorchMode(cameraId, false);
2487 if (res) {
2488 ALOGE("%s: torch client died but couldn't turn off torch: "
2489 "%s (%d)", __FUNCTION__, strerror(-res), res);
2490 return;
2491 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002492 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002493 break;
2494 }
2495 }
2496}
2497
Ruben Brunkcc776712015-02-17 20:18:47 -08002498/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002499
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002500 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002501 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2502 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002503 */
2504
Ruben Brunka8ca9152015-04-07 14:23:40 -07002505 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2506
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002507 // check torch client
2508 handleTorchClientBinderDied(who);
2509
2510 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002511 if(!evictClientIdByRemote(who)) {
2512 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002513 return;
2514 }
2515
Ruben Brunkcc776712015-02-17 20:18:47 -08002516 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2517 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002518}
2519
Ruben Brunkcc776712015-02-17 20:18:47 -08002520void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2521 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002522}
2523
Ruben Brunkcc776712015-02-17 20:18:47 -08002524void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2525 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2526 // Do not lock mServiceLock here or can get into a deadlock from
2527 // connect() -> disconnect -> updateStatus
2528
2529 auto state = getCameraState(cameraId);
2530
2531 if (state == nullptr) {
2532 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2533 cameraId.string());
2534 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002535 }
2536
Ruben Brunkcc776712015-02-17 20:18:47 -08002537 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2538 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2539 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2540 (const String8& cameraId, ICameraServiceListener::Status status) {
2541
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002542 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2543 // Update torch status if it has a flash unit.
2544 Mutex::Autolock al(mTorchStatusMutex);
2545 ICameraServiceListener::TorchStatus torchStatus;
2546 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2547 NAME_NOT_FOUND) {
2548 ICameraServiceListener::TorchStatus newTorchStatus =
2549 status == ICameraServiceListener::STATUS_PRESENT ?
2550 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2551 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2552 if (torchStatus != newTorchStatus) {
2553 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2554 }
2555 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002556 }
2557
2558 Mutex::Autolock lock(mStatusListenerLock);
2559
2560 for (auto& listener : mListenerList) {
2561 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2562 int id = cameraIdToInt(cameraId);
2563 if (id != -1) listener->onStatusChanged(status, id);
2564 }
2565 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002566}
2567
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002568void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2569 const String8& cameraId) {
2570 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2571 if (proxyBinder == nullptr) return;
2572 String16 id(cameraId);
2573 proxyBinder->notifyCameraState(id, newState);
2574}
2575
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002576status_t CameraService::getTorchStatusLocked(
2577 const String8& cameraId,
2578 ICameraServiceListener::TorchStatus *status) const {
2579 if (!status) {
2580 return BAD_VALUE;
2581 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002582 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2583 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002584 // invalid camera ID or the camera doesn't have a flash unit
2585 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002586 }
2587
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002588 *status = mTorchStatusMap.valueAt(index);
2589 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002590}
2591
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002592status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002593 ICameraServiceListener::TorchStatus status) {
2594 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2595 if (index == NAME_NOT_FOUND) {
2596 return BAD_VALUE;
2597 }
2598 ICameraServiceListener::TorchStatus& item =
2599 mTorchStatusMap.editValueAt(index);
2600 item = status;
2601
2602 return OK;
2603}
2604
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605}; // namespace android