blob: 4be2c92ff49c3dbe119ea5610f1c7699d1953c71 [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"
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
59namespace android {
60
61// ----------------------------------------------------------------------------
62// Logging support -- this is for debugging only
63// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070064volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070065
Steve Blockb8a80522011-12-20 16:23:08 +000066#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
67#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070068
69static void setLogLevel(int level) {
70 android_atomic_write(level, &gLogLevel);
71}
72
73// ----------------------------------------------------------------------------
74
Igor Murashkincba2c162013-03-20 15:56:31 -070075extern "C" {
76static void camera_device_status_change(
77 const struct camera_module_callbacks* callbacks,
78 int camera_id,
79 int new_status) {
80 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080081 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070082
Ruben Brunkcc776712015-02-17 20:18:47 -080083 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
84 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070085}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080086
87static void torch_mode_status_change(
88 const struct camera_module_callbacks* callbacks,
89 const char* camera_id,
90 int new_status) {
91 if (!callbacks || !camera_id) {
92 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
93 callbacks, camera_id);
94 }
95 sp<CameraService> cs = const_cast<CameraService*>(
96 static_cast<const CameraService*>(callbacks));
97
98 ICameraServiceListener::TorchStatus status;
99 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800100 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800101 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
102 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800103 case TORCH_MODE_STATUS_AVAILABLE_OFF:
104 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
105 break;
106 case TORCH_MODE_STATUS_AVAILABLE_ON:
107 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800108 break;
109 default:
110 ALOGE("Unknown torch status %d", new_status);
111 return;
112 }
113
114 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800115 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800116 status);
117}
Igor Murashkincba2c162013-03-20 15:56:31 -0700118} // extern "C"
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
122// This is ugly and only safe if we never re-create the CameraService, but
123// should be ok for now.
124static CameraService *gCameraService;
125
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800126CameraService::CameraService() :
127 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
128 mSoundRef(0), mModule(nullptr),
129 mNumberOfCameras(0), mNumberOfNormalCameras(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000130 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800132
Igor Murashkincba2c162013-03-20 15:56:31 -0700133 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800134 this->torch_mode_status_change = android::torch_mode_status_change;
135
Ruben Brunkcc776712015-02-17 20:18:47 -0800136 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137}
138
Iliyan Malchev8951a972011-04-14 16:55:59 -0700139void CameraService::onFirstRef()
140{
Ruben Brunkcc776712015-02-17 20:18:47 -0800141 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800142
Iliyan Malchev8951a972011-04-14 16:55:59 -0700143 BnCameraService::onFirstRef();
144
Ruben Brunk99e69712015-05-26 17:25:07 -0700145 // Update battery life tracking if service is restarting
146 BatteryNotifier& notifier(BatteryNotifier::getInstance());
147 notifier.noteResetCamera();
148 notifier.noteResetFlashlight();
149
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800150 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700151 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
152 (const hw_module_t **)&rawModule);
153 if (err < 0) {
154 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
155 logServiceError("Could not load camera HAL module", err);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700156 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700157 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800158
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700159 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 err = mModule->init();
161 if (err != OK) {
162 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
163 strerror(-err));
164 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800165
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700166 delete mModule;
167 mModule = nullptr;
168 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700169 }
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700170 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700171
172 mNumberOfCameras = mModule->getNumberOfCameras();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700173 mNumberOfNormalCameras = mNumberOfCameras;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700174
Yin-Chia Yehd4a653a2015-10-14 11:05:44 -0700175 // Setup vendor tags before we call get_camera_info the first time
176 // because HAL might need to setup static vendor keys in get_camera_info
177 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
178 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
179 setUpVendorTags();
180 }
181
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700182 mFlashlight = new CameraFlashlight(*mModule, *this);
183 status_t res = mFlashlight->findFlashUnits();
184 if (res) {
185 // impossible because we haven't open any camera devices.
186 ALOGE("Failed to find flash units.");
187 }
188
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700189 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700190 for (int i = 0; i < mNumberOfCameras; i++) {
191 String8 cameraId = String8::format("%d", i);
192
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700193 // Get camera info
194
195 struct camera_info info;
196 bool haveInfo = true;
197 status_t rc = mModule->getCameraInfo(i, &info);
198 if (rc != NO_ERROR) {
199 ALOGE("%s: Received error loading camera info for device %d, cost and"
200 " conflicting devices fields set to defaults for this device.",
201 __FUNCTION__, i);
202 haveInfo = false;
203 }
204
205 // Check for backwards-compatibility support
206 if (haveInfo) {
207 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
208 delete mModule;
209 mModule = nullptr;
210 return;
211 }
212 }
213
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700214 // Defaults to use for cost and conflicting devices
215 int cost = 100;
216 char** conflicting_devices = nullptr;
217 size_t conflicting_devices_length = 0;
218
219 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700220 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
221 cost = info.resource_cost;
222 conflicting_devices = info.conflicting_devices;
223 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700224 }
225
226 std::set<String8> conflicting;
227 for (size_t i = 0; i < conflicting_devices_length; i++) {
228 conflicting.emplace(String8(conflicting_devices[i]));
229 }
230
231 // Initialize state for each camera device
232 {
233 Mutex::Autolock lock(mCameraStatesLock);
234 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
235 conflicting));
236 }
237
238 if (mFlashlight->hasFlashUnit(cameraId)) {
239 mTorchStatusMap.add(cameraId,
240 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
241 }
242 }
243
244 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
245 mModule->setCallbacks(this);
246 }
247
Ruben Brunk2823ce02015-05-19 17:25:13 -0700248 CameraService::pingCameraServiceProxy();
249}
250
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700251sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Ruben Brunk2823ce02015-05-19 17:25:13 -0700252 sp<IServiceManager> sm = defaultServiceManager();
253 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
254 if (binder == nullptr) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700255 return nullptr;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700256 }
257 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700258 return proxyBinder;
259}
260
261void CameraService::pingCameraServiceProxy() {
262 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
263 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700264 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700265}
266
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800268 if (mModule) {
269 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800270 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800271 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800272 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800273 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274}
275
Ruben Brunkcc776712015-02-17 20:18:47 -0800276void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
277 camera_device_status_t newStatus) {
278 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700279 cameraId, newStatus);
280
Ruben Brunkcc776712015-02-17 20:18:47 -0800281 String8 id = String8::format("%d", cameraId);
282 std::shared_ptr<CameraState> state = getCameraState(id);
283
284 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700285 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
286 return;
287 }
288
Ruben Brunkcc776712015-02-17 20:18:47 -0800289 ICameraServiceListener::Status oldStatus = state->getStatus();
290
291 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
292 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700293 return;
294 }
295
Igor Murashkincba2c162013-03-20 15:56:31 -0700296 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700297 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
298 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800299 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700300 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800301 // Don't do this in updateStatus to avoid deadlock over mServiceLock
302 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700303
Ruben Brunkcc776712015-02-17 20:18:47 -0800304 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
305 // to this device until the status changes
306 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700307
Ruben Brunkcc776712015-02-17 20:18:47 -0800308 // Remove cached shim parameters
309 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700310
Ruben Brunkcc776712015-02-17 20:18:47 -0800311 // Remove the client from the list of active clients
312 clientToDisconnect = removeClientLocked(id);
313
314 // Notify the client of disconnection
315 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
316 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700317 }
318
Ruben Brunkcc776712015-02-17 20:18:47 -0800319 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
320 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700321
Ruben Brunkcc776712015-02-17 20:18:47 -0800322 // Disconnect client
323 if (clientToDisconnect.get() != nullptr) {
324 // Ensure not in binder RPC so client disconnect PID checks work correctly
325 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
326 "onDeviceStatusChanged must be called from the camera service process!");
327 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700328 }
329
Ruben Brunkcc776712015-02-17 20:18:47 -0800330 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700331 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
332 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
333 newStatus));
334 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800335 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700336 }
337
Igor Murashkincba2c162013-03-20 15:56:31 -0700338}
339
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800340void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800341 ICameraServiceListener::TorchStatus newStatus) {
342 Mutex::Autolock al(mTorchStatusMutex);
343 onTorchStatusChangedLocked(cameraId, newStatus);
344}
345
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800346void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800347 ICameraServiceListener::TorchStatus newStatus) {
348 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
349 __FUNCTION__, cameraId.string(), newStatus);
350
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800351 ICameraServiceListener::TorchStatus status;
352 status_t res = getTorchStatusLocked(cameraId, &status);
353 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700354 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
355 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800356 return;
357 }
358 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800359 return;
360 }
361
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800362 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800363 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800364 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
365 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800366 return;
367 }
368
Ruben Brunkcc776712015-02-17 20:18:47 -0800369 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700370 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700371 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700372 auto iter = mTorchUidMap.find(cameraId);
373 if (iter != mTorchUidMap.end()) {
374 int oldUid = iter->second.second;
375 int newUid = iter->second.first;
376 BatteryNotifier& notifier(BatteryNotifier::getInstance());
377 if (oldUid != newUid) {
378 // If the UID has changed, log the status and update current UID in mTorchUidMap
379 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
380 notifier.noteFlashlightOff(cameraId, oldUid);
381 }
382 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
383 notifier.noteFlashlightOn(cameraId, newUid);
384 }
385 iter->second.second = newUid;
386 } else {
387 // If the UID has not changed, log the status
388 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
389 notifier.noteFlashlightOn(cameraId, oldUid);
390 } else {
391 notifier.noteFlashlightOff(cameraId, oldUid);
392 }
393 }
394 }
395 }
396
397 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800398 Mutex::Autolock lock(mStatusListenerLock);
399 for (auto& i : mListenerList) {
400 i->onTorchStatusChanged(newStatus, String16{cameraId});
401 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800402 }
403}
404
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700406 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700407 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
408}
409
410int32_t CameraService::getNumberOfCameras(int type) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700411 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700412 switch (type) {
413 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
414 return mNumberOfNormalCameras;
415 case CAMERA_TYPE_ALL:
416 return mNumberOfCameras;
417 default:
418 ALOGW("%s: Unknown camera type %d, returning 0",
419 __FUNCTION__, type);
420 return 0;
421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422}
423
424status_t CameraService::getCameraInfo(int cameraId,
425 struct CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700426 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700427 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700428 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700429 }
430
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
432 return BAD_VALUE;
433 }
434
Iliyan Malchev8951a972011-04-14 16:55:59 -0700435 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700436 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800437 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700438 cameraInfo->facing = info.facing;
439 cameraInfo->orientation = info.orientation;
440 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441}
442
Ruben Brunkcc776712015-02-17 20:18:47 -0800443int CameraService::cameraIdToInt(const String8& cameraId) {
444 errno = 0;
445 size_t pos = 0;
446 int ret = stoi(std::string{cameraId.string()}, &pos);
447 if (errno != 0 || pos != cameraId.size()) {
448 return -1;
449 }
450 return ret;
451}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700452
453status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700454 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700455 status_t ret = OK;
456 struct CameraInfo info;
457 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
458 return ret;
459 }
460
461 CameraMetadata shimInfo;
462 int32_t orientation = static_cast<int32_t>(info.orientation);
463 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
464 return ret;
465 }
466
467 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
468 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
469 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
470 return ret;
471 }
472
Igor Murashkin65d14b92014-06-17 12:03:20 -0700473 CameraParameters shimParams;
474 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
475 // Error logged by callee
476 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700477 }
478
479 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700480 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700481 Vector<int32_t> formats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700482 {
483 shimParams.getSupportedPreviewSizes(/*out*/sizes);
484 shimParams.getSupportedPreviewFormats(/*out*/formats);
485 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700486 }
487
488 // Always include IMPLEMENTATION_DEFINED
489 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
490
491 const size_t INTS_PER_CONFIG = 4;
492
493 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700494 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
495
496 Vector<int32_t> streamConfigs;
497 streamConfigs.setCapacity(streamConfigSize);
498
Ruben Brunkb2119af2014-05-09 19:57:56 -0700499 for (size_t i = 0; i < formats.size(); ++i) {
500 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700501 streamConfigs.add(formats[i]);
502 streamConfigs.add(sizes[j].width);
503 streamConfigs.add(sizes[j].height);
504 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700505 }
506 }
507
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700508 for (size_t i = 0; i < jpegSizes.size(); ++i) {
509 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
510 streamConfigs.add(jpegSizes[i].width);
511 streamConfigs.add(jpegSizes[i].height);
512 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
513 }
514
Ruben Brunkb2119af2014-05-09 19:57:56 -0700515 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700516 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700517 return ret;
518 }
519
520 int64_t fakeMinFrames[0];
521 // TODO: Fixme, don't fake min frame durations.
522 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
523 fakeMinFrames, 0)) != OK) {
524 return ret;
525 }
526
527 int64_t fakeStalls[0];
528 // TODO: Fixme, don't fake stall durations.
529 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
530 fakeStalls, 0)) != OK) {
531 return ret;
532 }
533
534 *cameraInfo = shimInfo;
535 return OK;
536}
537
Zhijun He2b59be82013-09-25 10:14:30 -0700538status_t CameraService::getCameraCharacteristics(int cameraId,
539 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700540 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700541 if (!cameraInfo) {
542 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
543 return BAD_VALUE;
544 }
545
546 if (!mModule) {
547 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
548 return -ENODEV;
549 }
550
Zhijun He2b59be82013-09-25 10:14:30 -0700551 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
552 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
553 return BAD_VALUE;
554 }
555
556 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700557 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800558 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800559 getDeviceVersion(cameraId, &facing) < CAMERA_DEVICE_API_VERSION_3_0) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700560 /**
561 * Backwards compatibility mode for old HALs:
562 * - Convert CameraInfo into static CameraMetadata properties.
563 * - Retrieve cached CameraParameters for this camera. If none exist,
564 * attempt to open CameraClient and retrieve the CameraParameters.
565 * - Convert cached CameraParameters into static CameraMetadata
566 * properties.
567 */
568 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700569
Ruben Brunkb2119af2014-05-09 19:57:56 -0700570 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
571 return ret;
572 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700573
Ruben Brunkb2119af2014-05-09 19:57:56 -0700574 } else {
575 /**
576 * Normal HAL 2.1+ codepath.
577 */
578 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800579 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700580 *cameraInfo = info.static_camera_characteristics;
581 }
Zhijun He2b59be82013-09-25 10:14:30 -0700582
583 return ret;
584}
585
Ruben Brunkcc776712015-02-17 20:18:47 -0800586int CameraService::getCallingPid() {
587 return IPCThreadState::self()->getCallingPid();
588}
589
590int CameraService::getCallingUid() {
591 return IPCThreadState::self()->getCallingUid();
592}
593
594String8 CameraService::getFormattedCurrentTime() {
595 time_t now = time(nullptr);
596 char formattedTime[64];
597 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
598 return String8(formattedTime);
599}
600
601int CameraService::getCameraPriorityFromProcState(int procState) {
602 // Find the priority for the camera usage based on the process state. Higher priority clients
603 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700604 if (procState < 0) {
605 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
606 procState);
607 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800608 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700609 // Treat sleeping TOP processes the same as regular TOP processes, for
610 // access priority. This is important for lock-screen camera launch scenarios
611 if (procState == PROCESS_STATE_TOP_SLEEPING) {
612 procState = PROCESS_STATE_TOP;
613 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700614 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800615}
616
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800617status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700618 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800619 if (!mModule) {
620 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
621 return -ENODEV;
622 }
623
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800624 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
625 return OK;
626}
627
Igor Murashkin634a5152013-02-20 17:15:11 -0800628int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700629 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800630 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800631 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800632 return -1;
633 }
634
635 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800636 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800637 deviceVersion = info.device_version;
638 } else {
639 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
640 }
641
642 if (facing) {
643 *facing = info.facing;
644 }
645
646 return deviceVersion;
647}
648
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700649status_t CameraService::filterGetInfoErrorCode(status_t err) {
650 switch(err) {
651 case NO_ERROR:
652 case -EINVAL:
653 return err;
654 default:
655 break;
656 }
657 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800658}
659
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800660bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700661 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800662 vendor_tag_ops_t vOps = vendor_tag_ops_t();
663
664 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800665 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800666 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
667 return false;
668 }
669
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800670 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800671
672 // Ensure all vendor operations are present
673 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
674 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
675 vOps.get_tag_type == NULL) {
676 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
677 , __FUNCTION__);
678 return false;
679 }
680
681 // Read all vendor tag definitions into a descriptor
682 sp<VendorTagDescriptor> desc;
683 status_t res;
684 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
685 != OK) {
686 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
687 "received error %s (%d). Camera clients will not be able to use"
688 "vendor tags", __FUNCTION__, strerror(res), res);
689 return false;
690 }
691
692 // Set the global descriptor to use with camera metadata
693 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
694 return true;
695}
696
Ruben Brunkcc776712015-02-17 20:18:47 -0800697status_t CameraService::makeClient(const sp<CameraService>& cameraService,
698 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
699 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
700 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
701 /*out*/sp<BasicClient>* client) {
702
703 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
704 int id = cameraIdToInt(cameraId);
705 if (id == -1) {
706 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
707 cameraId.string());
708 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700709 }
710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711 if (halVersion < 0 || halVersion == deviceVersion) {
712 // Default path: HAL version is unspecified by caller, create CameraClient
713 // based on device version reported by the HAL.
714 switch(deviceVersion) {
715 case CAMERA_DEVICE_API_VERSION_1_0:
716 if (effectiveApiLevel == API_1) { // Camera1 API route
717 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
718 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
719 clientPid, clientUid, getpid(), legacyMode);
720 } else { // Camera2 API route
721 ALOGW("Camera using old HAL version: %d", deviceVersion);
722 return -EOPNOTSUPP;
723 }
724 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800725 case CAMERA_DEVICE_API_VERSION_3_0:
726 case CAMERA_DEVICE_API_VERSION_3_1:
727 case CAMERA_DEVICE_API_VERSION_3_2:
728 case CAMERA_DEVICE_API_VERSION_3_3:
729 if (effectiveApiLevel == API_1) { // Camera1 API route
730 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
731 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
732 clientPid, clientUid, servicePid, legacyMode);
733 } else { // Camera2 API route
734 sp<ICameraDeviceCallbacks> tmp =
735 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
736 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
737 facing, clientPid, clientUid, servicePid);
738 }
739 break;
740 default:
741 // Should not be reachable
742 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
743 return INVALID_OPERATION;
744 }
745 } else {
746 // A particular HAL version is requested by caller. Create CameraClient
747 // based on the requested HAL version.
748 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
749 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
750 // Only support higher HAL version device opened as HAL1.0 device.
751 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
752 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
753 clientPid, clientUid, servicePid, legacyMode);
754 } else {
755 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
756 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
757 " opened as HAL %x device", halVersion, deviceVersion,
758 CAMERA_DEVICE_API_VERSION_1_0);
759 return INVALID_OPERATION;
760 }
761 }
762 return NO_ERROR;
763}
764
Ruben Brunk6267b532015-04-30 17:44:07 -0700765String8 CameraService::toString(std::set<userid_t> intSet) {
766 String8 s("");
767 bool first = true;
768 for (userid_t i : intSet) {
769 if (first) {
770 s.appendFormat("%d", i);
771 first = false;
772 } else {
773 s.appendFormat(", %d", i);
774 }
775 }
776 return s;
777}
778
Ruben Brunkcc776712015-02-17 20:18:47 -0800779status_t CameraService::initializeShimMetadata(int cameraId) {
780 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700781
782 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800783 String8 id = String8::format("%d", cameraId);
784 status_t ret = NO_ERROR;
785 sp<Client> tmp = nullptr;
786 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
787 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
788 false, true, tmp)) != NO_ERROR) {
789 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
790 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700791 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800792 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700793}
794
Igor Murashkin65d14b92014-06-17 12:03:20 -0700795status_t CameraService::getLegacyParametersLazy(int cameraId,
796 /*out*/
797 CameraParameters* parameters) {
798
799 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
800
801 status_t ret = 0;
802
803 if (parameters == NULL) {
804 ALOGE("%s: parameters must not be null", __FUNCTION__);
805 return BAD_VALUE;
806 }
807
Ruben Brunkcc776712015-02-17 20:18:47 -0800808 String8 id = String8::format("%d", cameraId);
809
810 // Check if we already have parameters
811 {
812 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700813 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 auto cameraState = getCameraState(id);
815 if (cameraState == nullptr) {
816 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
817 return BAD_VALUE;
818 }
819 CameraParameters p = cameraState->getShimParams();
820 if (!p.isEmpty()) {
821 *parameters = p;
822 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700823 }
824 }
825
Ruben Brunkcc776712015-02-17 20:18:47 -0800826 int64_t token = IPCThreadState::self()->clearCallingIdentity();
827 ret = initializeShimMetadata(cameraId);
828 IPCThreadState::self()->restoreCallingIdentity(token);
829 if (ret != NO_ERROR) {
830 // Error already logged by callee
831 return ret;
832 }
833
834 // Check for parameters again
835 {
836 // Scope for service lock
837 Mutex::Autolock lock(mServiceLock);
838 auto cameraState = getCameraState(id);
839 if (cameraState == nullptr) {
840 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
841 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700842 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800843 CameraParameters p = cameraState->getShimParams();
844 if (!p.isEmpty()) {
845 *parameters = p;
846 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700847 }
848 }
849
Ruben Brunkcc776712015-02-17 20:18:47 -0800850 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
851 __FUNCTION__);
852 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700853}
854
Ruben Brunk36597b22015-03-20 22:15:57 -0700855status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
856 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800857
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500859
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800860 if (clientUid == USE_CALLING_UID) {
861 clientUid = getCallingUid();
862 } else {
863 // We only trust our own process to forward client UIDs
864 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700865 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
866 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700867 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800868 }
869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870
Iliyan Malchev8951a972011-04-14 16:55:59 -0700871 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800872 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
873 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700874 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700875 }
876
Ruben Brunkcc776712015-02-17 20:18:47 -0800877 if (getCameraState(cameraId) == nullptr) {
878 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
879 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700880 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 }
882
Ruben Brunk6267b532015-04-30 17:44:07 -0700883 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800884
Ruben Brunka8ca9152015-04-07 14:23:40 -0700885 // Only allow clients who are being used by the current foreground device user, unless calling
886 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700887 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
888 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
889 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
890 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700891 return PERMISSION_DENIED;
892 }
893
Ruben Brunkcc776712015-02-17 20:18:47 -0800894 return checkIfDeviceIsUsable(cameraId);
895}
896
897status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
898 auto cameraState = getCameraState(cameraId);
899 int callingPid = getCallingPid();
900 if (cameraState == nullptr) {
901 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
902 cameraId.string());
903 return -ENODEV;
904 }
905
906 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700907 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800908 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
909 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700910 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700911 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800912 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
913 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700914 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700915 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700916
Ruben Brunkcc776712015-02-17 20:18:47 -0800917 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800918}
919
Ruben Brunkcc776712015-02-17 20:18:47 -0800920void CameraService::finishConnectLocked(const sp<BasicClient>& client,
921 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800922
Ruben Brunkcc776712015-02-17 20:18:47 -0800923 // Make a descriptor for the incoming client
924 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
925 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
926
927 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
928 String8(client->getPackageName()));
929
930 if (evicted.size() > 0) {
931 // This should never happen - clients should already have been removed in disconnect
932 for (auto& i : evicted) {
933 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
934 __FUNCTION__, i->getKey().string());
935 }
936
937 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
938 __FUNCTION__);
939 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700940
941 // And register a death notification for the client callback. Do
942 // this last to avoid Binder policy where a nested Binder
943 // transaction might be pre-empted to service the client death
944 // notification if the client process dies before linkToDeath is
945 // invoked.
946 sp<IBinder> remoteCallback = client->getRemote();
947 if (remoteCallback != nullptr) {
948 remoteCallback->linkToDeath(this);
949 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800950}
951
952status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
953 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
954 /*out*/
955 sp<BasicClient>* client,
956 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700957 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800958 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700959 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800960 DescriptorPtr clientDescriptor;
961 {
962 if (effectiveApiLevel == API_1) {
963 // If we are using API1, any existing client for this camera ID with the same remote
964 // should be returned rather than evicted to allow MediaRecorder to work properly.
965
966 auto current = mActiveClientManager.get(cameraId);
967 if (current != nullptr) {
968 auto clientSp = current->getValue();
969 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700970 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
971 ALOGW("CameraService connect called from same client, but with a different"
972 " API level, evicting prior client...");
973 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800974 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700975 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800976 *client = clientSp;
977 return NO_ERROR;
978 }
979 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800980 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800981 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800982
Ruben Brunkcc776712015-02-17 20:18:47 -0800983 // Return error if the device was unplugged or removed by the HAL for some reason
984 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
985 return ret;
986 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800987
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 // Get current active client PIDs
989 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
990 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800991
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700992 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
993 // address of PROCESS_STATE_NONEXISTENT as a reference argument
994 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
995 // not have an out-of-class definition.
996 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800997
Ruben Brunkcc776712015-02-17 20:18:47 -0800998 // Get priorites of all active PIDs
999 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1000 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001001
Ruben Brunkcc776712015-02-17 20:18:47 -08001002 // Update all active clients' priorities
1003 std::map<int,int> pidToPriorityMap;
1004 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1005 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1006 }
1007 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001008
Ruben Brunkcc776712015-02-17 20:18:47 -08001009 // Get state for the given cameraId
1010 auto state = getCameraState(cameraId);
1011 if (state == nullptr) {
1012 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1013 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001014 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001015 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001016
1017 // Make descriptor for incoming client
1018 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1019 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1020 state->getConflicting(),
1021 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1022
1023 // Find clients that would be evicted
1024 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1025
1026 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1027 // background, so we cannot do evictions
1028 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1029 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1030 " priority).", clientPid);
1031
1032 sp<BasicClient> clientSp = clientDescriptor->getValue();
1033 String8 curTime = getFormattedCurrentTime();
1034 auto incompatibleClients =
1035 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1036
1037 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001038 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001039 cameraId.string(), packageName.string(), clientPid,
1040 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1041
1042 for (auto& i : incompatibleClients) {
1043 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1044 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1045 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1046 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001047 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1048 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1049 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1050 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 }
1052
1053 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001054 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001055 mEventLog.add(msg);
1056
1057 return -EBUSY;
1058 }
1059
1060 for (auto& i : evicted) {
1061 sp<BasicClient> clientSp = i->getValue();
1062 if (clientSp.get() == nullptr) {
1063 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1064
1065 // TODO: Remove this
1066 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1067 __FUNCTION__);
1068 mActiveClientManager.remove(i);
1069 continue;
1070 }
1071
1072 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1073 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001074 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001075
Ruben Brunkcc776712015-02-17 20:18:47 -08001076 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001077 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1078 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1079 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001080 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1081 i->getOwnerId(), i->getPriority(), cameraId.string(),
1082 packageName.string(), clientPid,
1083 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1084
1085 // Notify the client of disconnection
1086 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1087 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001088 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001089 }
1090
Ruben Brunkcc776712015-02-17 20:18:47 -08001091 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1092 // other clients from connecting in mServiceLockWrapper if held
1093 mServiceLock.unlock();
1094
1095 // Clear caller identity temporarily so client disconnect PID checks work correctly
1096 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1097
1098 // Destroy evicted clients
1099 for (auto& i : evictedClients) {
1100 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001101 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001102 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001103
1104 IPCThreadState::self()->restoreCallingIdentity(token);
1105
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001106 for (const auto& i : evictedClients) {
1107 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1108 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1109 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1110 if (ret == TIMED_OUT) {
1111 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1112 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1113 mActiveClientManager.toString().string());
1114 return -EBUSY;
1115 }
1116 if (ret != NO_ERROR) {
1117 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1118 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1119 ret, mActiveClientManager.toString().string());
1120 return ret;
1121 }
1122 }
1123
1124 evictedClients.clear();
1125
Ruben Brunkcc776712015-02-17 20:18:47 -08001126 // Once clients have been disconnected, relock
1127 mServiceLock.lock();
1128
1129 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1130 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1131 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001132 }
1133
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 *partial = clientDescriptor;
1135 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001136}
1137
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001138status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001139 const sp<ICameraClient>& cameraClient,
1140 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001141 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001142 int clientUid,
1143 /*out*/
1144 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001145
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001146 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001147 status_t ret = NO_ERROR;
1148 String8 id = String8::format("%d", cameraId);
1149 sp<Client> client = nullptr;
1150 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001151 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001152
Ruben Brunkcc776712015-02-17 20:18:47 -08001153 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001154 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001155 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001156 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 }
1158
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001159 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001160 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161}
1162
Zhijun Heb10cdad2014-06-16 16:38:35 -07001163status_t CameraService::connectLegacy(
1164 const sp<ICameraClient>& cameraClient,
1165 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001166 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001167 int clientUid,
1168 /*out*/
1169 sp<ICamera>& device) {
1170
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001171 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001172 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001173 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001174 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001175 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001176 /*
1177 * Either the HAL version is unspecified in which case this just creates
1178 * a camera client selected by the latest device version, or
1179 * it's a particular version in which case the HAL must supported
1180 * the open_legacy call
1181 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001182 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001183 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001184 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001185 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001186 return INVALID_OPERATION;
1187 }
1188
Ruben Brunkcc776712015-02-17 20:18:47 -08001189 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001191 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001192 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001193
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;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001198 }
1199
Zhijun Heb10cdad2014-06-16 16:38:35 -07001200 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001201 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001202}
1203
Ruben Brunkcc776712015-02-17 20:18:47 -08001204status_t CameraService::connectDevice(
1205 const sp<ICameraDeviceCallbacks>& cameraCb,
1206 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001207 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001208 int clientUid,
1209 /*out*/
1210 sp<ICameraDeviceUser>& device) {
1211
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001212 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001213 status_t ret = NO_ERROR;
1214 String8 id = String8::format("%d", cameraId);
1215 sp<CameraDeviceClient> client = nullptr;
1216 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001217 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001218 /*out*/client);
1219
1220 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001221 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001222 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001223 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001224 }
1225
Ruben Brunkcc776712015-02-17 20:18:47 -08001226 device = client;
1227 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001228}
1229
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001230status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1231 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001232
1233 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001234 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001235 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001236 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001237 }
1238
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001239 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001240 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001241
1242 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001243 auto state = getCameraState(id);
1244 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001245 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001246 return -EINVAL;
1247 }
1248
1249 ICameraServiceListener::Status cameraStatus = state->getStatus();
1250 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1251 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001252 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001253 return -EINVAL;
1254 }
1255
1256 {
1257 Mutex::Autolock al(mTorchStatusMutex);
1258 ICameraServiceListener::TorchStatus status;
1259 status_t res = getTorchStatusLocked(id, &status);
1260 if (res) {
1261 ALOGE("%s: getting current torch status failed for camera %s",
1262 __FUNCTION__, id.string());
1263 return -EINVAL;
1264 }
1265
1266 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001267 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001268 ALOGE("%s: torch mode of camera %s is not available because "
1269 "camera is in use", __FUNCTION__, id.string());
1270 return -EBUSY;
1271 } else {
1272 ALOGE("%s: torch mode of camera %s is not available due to "
1273 "insufficient resources", __FUNCTION__, id.string());
1274 return -EUSERS;
1275 }
1276 }
1277 }
1278
Ruben Brunk99e69712015-05-26 17:25:07 -07001279 {
1280 // Update UID map - this is used in the torch status changed callbacks, so must be done
1281 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001282 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001283 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1284 mTorchUidMap[id].first = uid;
1285 mTorchUidMap[id].second = uid;
1286 } else {
1287 // Set the pending UID
1288 mTorchUidMap[id].first = uid;
1289 }
1290 }
1291
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001292 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001293
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001294 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001295 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1296 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001297 return res;
1298 }
1299
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001300 {
1301 // update the link to client's death
1302 Mutex::Autolock al(mTorchClientMapMutex);
1303 ssize_t index = mTorchClientMap.indexOfKey(id);
1304 if (enabled) {
1305 if (index == NAME_NOT_FOUND) {
1306 mTorchClientMap.add(id, clientBinder);
1307 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001308 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001309 mTorchClientMap.replaceValueAt(index, clientBinder);
1310 }
1311 clientBinder->linkToDeath(this);
1312 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001313 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001314 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001315 }
1316
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001317 return OK;
1318}
1319
Ruben Brunk6267b532015-04-30 17:44:07 -07001320void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001321 ATRACE_CALL();
1322
Ruben Brunk36597b22015-03-20 22:15:57 -07001323 switch(eventId) {
1324 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001325 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001326 break;
1327 }
1328 case ICameraService::NO_EVENT:
1329 default: {
1330 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1331 eventId);
1332 break;
1333 }
1334 }
1335}
1336
Ruben Brunk99e69712015-05-26 17:25:07 -07001337status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001338 ATRACE_CALL();
1339
Igor Murashkinbfc99152013-02-27 12:55:20 -08001340 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001341
Ruben Brunk3450ba72015-06-16 11:00:37 -07001342 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001343 ALOGE("%s: Listener must not be null", __FUNCTION__);
1344 return BAD_VALUE;
1345 }
1346
Igor Murashkinbfc99152013-02-27 12:55:20 -08001347 Mutex::Autolock lock(mServiceLock);
1348
Ruben Brunkcc776712015-02-17 20:18:47 -08001349 {
1350 Mutex::Autolock lock(mStatusListenerLock);
1351 for (auto& it : mListenerList) {
1352 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1353 ALOGW("%s: Tried to add listener %p which was already subscribed",
1354 __FUNCTION__, listener.get());
1355 return ALREADY_EXISTS;
1356 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001357 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001358
1359 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001360 }
1361
Igor Murashkinbfc99152013-02-27 12:55:20 -08001362
Igor Murashkincba2c162013-03-20 15:56:31 -07001363 /* Immediately signal current status to this listener only */
1364 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001365 Mutex::Autolock lock(mCameraStatesLock);
1366 for (auto& i : mCameraStates) {
1367 // TODO: Update binder to use String16 for camera IDs and remove;
1368 int id = cameraIdToInt(i.first);
1369 if (id == -1) continue;
1370
1371 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001372 }
1373 }
1374
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001375 /* Immediately signal current torch status to this listener only */
1376 {
1377 Mutex::Autolock al(mTorchStatusMutex);
1378 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001379 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1380 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001381 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001382 }
1383
Igor Murashkinbfc99152013-02-27 12:55:20 -08001384 return OK;
1385}
Ruben Brunkcc776712015-02-17 20:18:47 -08001386
1387status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001388 ATRACE_CALL();
1389
Igor Murashkinbfc99152013-02-27 12:55:20 -08001390 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1391
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001392 if (listener == 0) {
1393 ALOGE("%s: Listener must not be null", __FUNCTION__);
1394 return BAD_VALUE;
1395 }
1396
Igor Murashkinbfc99152013-02-27 12:55:20 -08001397 Mutex::Autolock lock(mServiceLock);
1398
Ruben Brunkcc776712015-02-17 20:18:47 -08001399 {
1400 Mutex::Autolock lock(mStatusListenerLock);
1401 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1402 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1403 mListenerList.erase(it);
1404 return OK;
1405 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001406 }
1407 }
1408
1409 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1410 __FUNCTION__, listener.get());
1411
1412 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001413}
1414
Ruben Brunkcc776712015-02-17 20:18:47 -08001415status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001416
1417 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001418 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1419
1420 if (parameters == NULL) {
1421 ALOGE("%s: parameters must not be null", __FUNCTION__);
1422 return BAD_VALUE;
1423 }
1424
1425 status_t ret = 0;
1426
1427 CameraParameters shimParams;
1428 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1429 // Error logged by caller
1430 return ret;
1431 }
1432
1433 String8 shimParamsString8 = shimParams.flatten();
1434 String16 shimParamsString16 = String16(shimParamsString8);
1435
1436 *parameters = shimParamsString16;
1437
1438 return OK;
1439}
1440
1441status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001442 ATRACE_CALL();
1443
Igor Murashkin65d14b92014-06-17 12:03:20 -07001444 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1445
1446 switch (apiVersion) {
1447 case API_VERSION_1:
1448 case API_VERSION_2:
1449 break;
1450 default:
1451 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1452 return BAD_VALUE;
1453 }
1454
1455 int facing = -1;
1456 int deviceVersion = getDeviceVersion(cameraId, &facing);
1457
1458 switch(deviceVersion) {
1459 case CAMERA_DEVICE_API_VERSION_1_0:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001460 case CAMERA_DEVICE_API_VERSION_3_0:
1461 case CAMERA_DEVICE_API_VERSION_3_1:
1462 if (apiVersion == API_VERSION_2) {
1463 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1464 __FUNCTION__, cameraId);
1465 return -EOPNOTSUPP;
1466 } else { // if (apiVersion == API_VERSION_1) {
1467 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1468 __FUNCTION__, cameraId);
1469 return OK;
1470 }
1471 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001472 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001473 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1474 __FUNCTION__, cameraId);
1475 return OK;
1476 case -1:
1477 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1478 return BAD_VALUE;
1479 default:
1480 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1481 return INVALID_OPERATION;
1482 }
1483
1484 return OK;
1485}
1486
Ruben Brunkcc776712015-02-17 20:18:47 -08001487void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001488 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001489 for (auto& i : mActiveClientManager.getAll()) {
1490 auto clientSp = i->getValue();
1491 if (clientSp.get() == client) {
1492 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001493 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001494 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001495}
1496
Ruben Brunkcc776712015-02-17 20:18:47 -08001497bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1498 const int callingPid = getCallingPid();
1499 const int servicePid = getpid();
1500 bool ret = false;
1501 {
1502 // Acquire mServiceLock and prevent other clients from connecting
1503 std::unique_ptr<AutoConditionLock> lock =
1504 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001505
Igor Murashkin634a5152013-02-20 17:15:11 -08001506
Ruben Brunkcc776712015-02-17 20:18:47 -08001507 std::vector<sp<BasicClient>> evicted;
1508 for (auto& i : mActiveClientManager.getAll()) {
1509 auto clientSp = i->getValue();
1510 if (clientSp.get() == nullptr) {
1511 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1512 mActiveClientManager.remove(i);
1513 continue;
1514 }
1515 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1516 callingPid == clientSp->getClientPid())) {
1517 mActiveClientManager.remove(i);
1518 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 // Notify the client of disconnection
1521 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1522 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001523 }
1524 }
1525
Ruben Brunkcc776712015-02-17 20:18:47 -08001526 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1527 // other clients from connecting in mServiceLockWrapper if held
1528 mServiceLock.unlock();
1529
Ruben Brunk36597b22015-03-20 22:15:57 -07001530 // Do not clear caller identity, remote caller should be client proccess
1531
Ruben Brunkcc776712015-02-17 20:18:47 -08001532 for (auto& i : evicted) {
1533 if (i.get() != nullptr) {
1534 i->disconnect();
1535 ret = true;
1536 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001537 }
1538
Ruben Brunkcc776712015-02-17 20:18:47 -08001539 // Reacquire mServiceLock
1540 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001541
Ruben Brunkcc776712015-02-17 20:18:47 -08001542 } // lock is destroyed, allow further connect calls
1543
1544 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001545}
1546
Igor Murashkinecf17e82012-10-02 16:05:11 -07001547
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001548/**
1549 * Check camera capabilities, such as support for basic color operation
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001550 * Also check that the device HAL version is still in support
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001551 */
1552int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
Yin-Chia Yeh654b4bf2015-12-08 12:19:31 -08001553 // device_version undefined in CAMERA_MODULE_API_VERSION_1_0,
1554 // All CAMERA_MODULE_API_VERSION_1_0 devices are backward-compatible
1555 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
1556 // Verify the device version is in the supported range
1557 switch (info.device_version) {
1558 case CAMERA_DEVICE_API_VERSION_1_0:
1559 case CAMERA_DEVICE_API_VERSION_3_0:
1560 case CAMERA_DEVICE_API_VERSION_3_1:
1561 case CAMERA_DEVICE_API_VERSION_3_2:
1562 case CAMERA_DEVICE_API_VERSION_3_3:
1563 // in support
1564 break;
1565 case CAMERA_DEVICE_API_VERSION_2_0:
1566 case CAMERA_DEVICE_API_VERSION_2_1:
1567 // no longer supported
1568 default:
1569 ALOGE("%s: Device %d has HAL version %x, which is not supported",
1570 __FUNCTION__, id, info.device_version);
1571 String8 msg = String8::format(
1572 "Unsupported device HAL version %x for device %d",
1573 info.device_version, id);
1574 logServiceError(msg.string(), NO_INIT);
1575 return NO_INIT;
1576 }
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001577 }
1578
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001579 // Assume all devices pre-v3.3 are backward-compatible
1580 bool isBackwardCompatible = true;
1581 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1582 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1583 isBackwardCompatible = false;
1584 status_t res;
1585 camera_metadata_ro_entry_t caps;
1586 res = find_camera_metadata_ro_entry(
1587 info.static_camera_characteristics,
1588 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1589 &caps);
1590 if (res != 0) {
1591 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1592 __FUNCTION__, id);
1593 caps.count = 0;
1594 }
1595 for (size_t i = 0; i < caps.count; i++) {
1596 if (caps.data.u8[i] ==
1597 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1598 isBackwardCompatible = true;
1599 break;
1600 }
1601 }
1602 }
1603
1604 if (!isBackwardCompatible) {
1605 mNumberOfNormalCameras--;
1606 *latestStrangeCameraId = id;
1607 } else {
1608 if (id > *latestStrangeCameraId) {
1609 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1610 "This is not allowed due backward-compatibility requirements",
1611 __FUNCTION__, id, *latestStrangeCameraId);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001612 logServiceError("Invalid order of camera devices", NO_INIT);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001613 mNumberOfCameras = 0;
1614 mNumberOfNormalCameras = 0;
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001615 return NO_INIT;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001616 }
1617 }
1618 return OK;
1619}
1620
Ruben Brunkcc776712015-02-17 20:18:47 -08001621std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1622 const String8& cameraId) const {
1623 std::shared_ptr<CameraState> state;
1624 {
1625 Mutex::Autolock lock(mCameraStatesLock);
1626 auto iter = mCameraStates.find(cameraId);
1627 if (iter != mCameraStates.end()) {
1628 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 }
1630 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001631 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632}
1633
Ruben Brunkcc776712015-02-17 20:18:47 -08001634sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1635 // Remove from active clients list
1636 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1637 if (clientDescriptorPtr == nullptr) {
1638 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1639 cameraId.string());
1640 return sp<BasicClient>{nullptr};
1641 }
1642
1643 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001644}
1645
Ruben Brunk6267b532015-04-30 17:44:07 -07001646void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001647 // Acquire mServiceLock and prevent other clients from connecting
1648 std::unique_ptr<AutoConditionLock> lock =
1649 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1650
Ruben Brunk6267b532015-04-30 17:44:07 -07001651 std::set<userid_t> newAllowedUsers;
1652 for (size_t i = 0; i < length; i++) {
1653 if (newUserId[i] < 0) {
1654 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1655 __FUNCTION__, newUserId[i]);
1656 return;
1657 }
1658 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001659 }
1660
Ruben Brunka8ca9152015-04-07 14:23:40 -07001661
Ruben Brunk6267b532015-04-30 17:44:07 -07001662 if (newAllowedUsers == mAllowedUsers) {
1663 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1664 return;
1665 }
1666
1667 logUserSwitch(mAllowedUsers, newAllowedUsers);
1668
1669 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001670
1671 // Current user has switched, evict all current clients.
1672 std::vector<sp<BasicClient>> evicted;
1673 for (auto& i : mActiveClientManager.getAll()) {
1674 auto clientSp = i->getValue();
1675
1676 if (clientSp.get() == nullptr) {
1677 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1678 continue;
1679 }
1680
Ruben Brunk6267b532015-04-30 17:44:07 -07001681 // Don't evict clients that are still allowed.
1682 uid_t clientUid = clientSp->getClientUid();
1683 userid_t clientUserId = multiuser_get_user_id(clientUid);
1684 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1685 continue;
1686 }
1687
Ruben Brunk36597b22015-03-20 22:15:57 -07001688 evicted.push_back(clientSp);
1689
1690 String8 curTime = getFormattedCurrentTime();
1691
1692 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1693 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001694
Ruben Brunk36597b22015-03-20 22:15:57 -07001695 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001696 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001697 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001698 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1699 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001700
1701 }
1702
1703 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1704 // blocking other clients from connecting in mServiceLockWrapper if held.
1705 mServiceLock.unlock();
1706
1707 // Clear caller identity temporarily so client disconnect PID checks work correctly
1708 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1709
1710 for (auto& i : evicted) {
1711 i->disconnect();
1712 }
1713
1714 IPCThreadState::self()->restoreCallingIdentity(token);
1715
1716 // Reacquire mServiceLock
1717 mServiceLock.lock();
1718}
Ruben Brunkcc776712015-02-17 20:18:47 -08001719
Ruben Brunka8ca9152015-04-07 14:23:40 -07001720void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001721 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001722 Mutex::Autolock l(mLogLock);
1723 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724}
1725
Ruben Brunka8ca9152015-04-07 14:23:40 -07001726void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001727 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001728 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001729 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001730 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001731}
1732
1733void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001734 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001735 // Log the clients evicted
1736 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001737 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001738}
1739
1740void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001741 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001742 // Log the client rejected
1743 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001744 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001745}
1746
Ruben Brunk6267b532015-04-30 17:44:07 -07001747void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1748 const std::set<userid_t>& newUserIds) {
1749 String8 newUsers = toString(newUserIds);
1750 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001751 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001752 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1753 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001754}
1755
1756void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1757 // Log the device removal
1758 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1759}
1760
1761void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1762 // Log the device removal
1763 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1764}
1765
1766void CameraService::logClientDied(int clientPid, const char* reason) {
1767 // Log the device removal
1768 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001769}
1770
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001771void CameraService::logServiceError(const char* msg, int errorCode) {
1772 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001773 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001774}
1775
Ruben Brunk36597b22015-03-20 22:15:57 -07001776status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1777 uint32_t flags) {
1778
1779 const int pid = getCallingPid();
1780 const int selfPid = getpid();
1781
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782 // Permission checks
1783 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001784 case BnCameraService::CONNECT:
1785 case BnCameraService::CONNECT_DEVICE:
1786 case BnCameraService::CONNECT_LEGACY: {
1787 if (pid != selfPid) {
1788 // we're called from a different process, do the real check
1789 if (!checkCallingPermission(
1790 String16("android.permission.CAMERA"))) {
1791 const int uid = getCallingUid();
1792 ALOGE("Permission Denial: "
1793 "can't use the camera pid=%d, uid=%d", pid, uid);
1794 return PERMISSION_DENIED;
1795 }
1796 }
1797 break;
1798 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001799 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1800 if (pid != selfPid) {
1801 // Ensure we're being called by system_server, or similar process with
1802 // permissions to notify the camera service about system events
1803 if (!checkCallingPermission(
1804 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1805 const int uid = getCallingUid();
1806 ALOGE("Permission Denial: cannot send updates to camera service about system"
1807 " events from pid=%d, uid=%d", pid, uid);
1808 return PERMISSION_DENIED;
1809 }
1810 }
1811 break;
1812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 }
1814
1815 return BnCameraService::onTransact(code, data, reply, flags);
1816}
1817
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818// We share the media players for shutter and recording sound for all clients.
1819// A reference count is kept to determine when we will actually release the
1820// media players.
1821
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001822MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001824 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001825 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 mp->prepare();
1827 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001828 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829 return NULL;
1830 }
1831 return mp;
1832}
1833
1834void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001835 ATRACE_CALL();
1836
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 Mutex::Autolock lock(mSoundLock);
1838 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1839 if (mSoundRef++) return;
1840
1841 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001842 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1843 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844}
1845
1846void CameraService::releaseSound() {
1847 Mutex::Autolock lock(mSoundLock);
1848 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1849 if (--mSoundRef) return;
1850
1851 for (int i = 0; i < NUM_SOUNDS; i++) {
1852 if (mSoundPlayer[i] != 0) {
1853 mSoundPlayer[i]->disconnect();
1854 mSoundPlayer[i].clear();
1855 }
1856 }
1857}
1858
1859void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001860 ATRACE_CALL();
1861
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 LOG1("playSound(%d)", kind);
1863 Mutex::Autolock lock(mSoundLock);
1864 sp<MediaPlayer> player = mSoundPlayer[kind];
1865 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001866 player->seekTo(0);
1867 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 }
1869}
1870
1871// ----------------------------------------------------------------------------
1872
1873CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001874 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001875 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001876 int cameraId, int cameraFacing,
1877 int clientPid, uid_t clientUid,
1878 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001879 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001880 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001881 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001882 cameraId, cameraFacing,
1883 clientPid, clientUid,
1884 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001885{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001887 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001889 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001892
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001893 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894}
1895
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896// tear down the client
1897CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001898 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001899 mDestructionStarted = true;
1900
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001901 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001902 // unconditionally disconnect. function is idempotent
1903 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904}
1905
Igor Murashkin634a5152013-02-20 17:15:11 -08001906CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001907 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001908 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001909 int cameraId, int cameraFacing,
1910 int clientPid, uid_t clientUid,
1911 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001912 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001913{
1914 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001915 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001916 mCameraId = cameraId;
1917 mCameraFacing = cameraFacing;
1918 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001919 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001920 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001921 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001922 mDestructionStarted = false;
1923}
1924
1925CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001926 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001927 mDestructionStarted = true;
1928}
1929
1930void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001931 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001932 return;
1933 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001934 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001935
1936 mCameraService->removeByClient(this);
1937 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001938 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001939
1940 sp<IBinder> remote = getRemote();
1941 if (remote != nullptr) {
1942 remote->unlinkToDeath(mCameraService);
1943 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001944
1945 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001946 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1947
Igor Murashkincba2c162013-03-20 15:56:31 -07001948 // client shouldn't be able to call into us anymore
1949 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001950}
1951
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08001952status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
1953 // No dumping of clients directly over Binder,
1954 // must go through CameraService::dump
1955 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
1956 IPCThreadState::self()->getCallingUid(), NULL, 0);
1957 return OK;
1958}
1959
Ruben Brunkcc776712015-02-17 20:18:47 -08001960String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001961 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001962}
1963
1964
1965int CameraService::BasicClient::getClientPid() const {
1966 return mClientPid;
1967}
1968
Ruben Brunk6267b532015-04-30 17:44:07 -07001969uid_t CameraService::BasicClient::getClientUid() const {
1970 return mClientUid;
1971}
1972
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001973bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1974 // Defaults to API2.
1975 return level == API_2;
1976}
1977
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001978status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001979 ATRACE_CALL();
1980
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001981 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001982 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001983 mOpsCallback = new OpsCallback(this);
1984
Igor Murashkine6800ce2013-03-04 17:25:57 -08001985 {
1986 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001987 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001988 }
1989
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001990 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001991 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001992 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001993 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001994
Svetoslav28e8ef72015-05-11 19:21:31 -07001995 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001996 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001997 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001998 return PERMISSION_DENIED;
1999 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002000
Svetoslav28e8ef72015-05-11 19:21:31 -07002001 if (res == AppOpsManager::MODE_IGNORED) {
2002 ALOGI("Camera %d: Access for \"%s\" has been restricted",
2003 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002004 // Return the same error as for device policy manager rejection
2005 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002006 }
2007
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002008 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002009
2010 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2011 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002012 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002013
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002014 // Transition device state to OPEN
2015 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2016 String8::format("%d", mCameraId));
2017
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002018 return OK;
2019}
2020
2021status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002022 ATRACE_CALL();
2023
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002024 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002025 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002026 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002027 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002028 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002029 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002030
Ruben Brunkcc776712015-02-17 20:18:47 -08002031 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2032 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002033
Ruben Brunkcc776712015-02-17 20:18:47 -08002034 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002035 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002036 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002037
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002038 // Transition device state to CLOSED
2039 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2040 String8::format("%d", mCameraId));
2041
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002042 // Notify flashlight that a camera device is closed.
2043 mCameraService->mFlashlight->deviceClosed(
2044 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002045 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002046 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002047 if (mOpsCallback != NULL) {
2048 mAppOpsManager.stopWatchingMode(mOpsCallback);
2049 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002050 mOpsCallback.clear();
2051
2052 return OK;
2053}
2054
2055void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002056 ATRACE_CALL();
2057
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002058 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002059 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002060
2061 if (op != AppOpsManager::OP_CAMERA) {
2062 ALOGW("Unexpected app ops notification received: %d", op);
2063 return;
2064 }
2065
2066 int32_t res;
2067 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002068 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002069 ALOGV("checkOp returns: %d, %s ", res,
2070 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2071 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2072 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2073 "UNKNOWN");
2074
2075 if (res != AppOpsManager::MODE_ALLOWED) {
2076 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2077 myName.string());
2078 // Reset the client PID to allow server-initiated disconnect,
2079 // and to prevent further calls by client.
2080 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002081 CaptureResultExtras resultExtras; // a dummy result (invalid)
2082 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002083 disconnect();
2084 }
2085}
2086
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087// ----------------------------------------------------------------------------
2088
Ruben Brunkcc776712015-02-17 20:18:47 -08002089// Provide client strong pointer for callbacks.
2090sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2091 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2092 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2093 if (clientDescriptor != nullptr) {
2094 return sp<Client>{
2095 static_cast<Client*>(clientDescriptor->getValue().get())};
2096 }
2097 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098}
2099
Jianing Weicb0652e2014-03-12 18:29:36 -07002100void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2101 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002102 (void) errorCode;
2103 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002104 if (mRemoteCallback != NULL) {
2105 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2106 } else {
2107 ALOGE("mRemoteCallback is NULL!!");
2108 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002109}
2110
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002111// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002112void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002113 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002114 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002115}
2116
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002117bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2118 return level == API_1;
2119}
2120
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002121CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2122 mClient(client) {
2123}
2124
2125void CameraService::Client::OpsCallback::opChanged(int32_t op,
2126 const String16& packageName) {
2127 sp<BasicClient> client = mClient.promote();
2128 if (client != NULL) {
2129 client->opChanged(op, packageName);
2130 }
2131}
2132
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002134// CameraState
2135// ----------------------------------------------------------------------------
2136
2137CameraService::CameraState::CameraState(const String8& id, int cost,
2138 const std::set<String8>& conflicting) : mId(id),
2139 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2140
2141CameraService::CameraState::~CameraState() {}
2142
2143ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2144 Mutex::Autolock lock(mStatusLock);
2145 return mStatus;
2146}
2147
2148CameraParameters CameraService::CameraState::getShimParams() const {
2149 return mShimParams;
2150}
2151
2152void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2153 mShimParams = params;
2154}
2155
2156int CameraService::CameraState::getCost() const {
2157 return mCost;
2158}
2159
2160std::set<String8> CameraService::CameraState::getConflicting() const {
2161 return mConflicting;
2162}
2163
2164String8 CameraService::CameraState::getId() const {
2165 return mId;
2166}
2167
2168// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002169// ClientEventListener
2170// ----------------------------------------------------------------------------
2171
2172void CameraService::ClientEventListener::onClientAdded(
2173 const resource_policy::ClientDescriptor<String8,
2174 sp<CameraService::BasicClient>>& descriptor) {
2175 auto basicClient = descriptor.getValue();
2176 if (basicClient.get() != nullptr) {
2177 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2178 notifier.noteStartCamera(descriptor.getKey(),
2179 static_cast<int>(basicClient->getClientUid()));
2180 }
2181}
2182
2183void CameraService::ClientEventListener::onClientRemoved(
2184 const resource_policy::ClientDescriptor<String8,
2185 sp<CameraService::BasicClient>>& descriptor) {
2186 auto basicClient = descriptor.getValue();
2187 if (basicClient.get() != nullptr) {
2188 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2189 notifier.noteStopCamera(descriptor.getKey(),
2190 static_cast<int>(basicClient->getClientUid()));
2191 }
2192}
2193
2194
2195// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002196// CameraClientManager
2197// ----------------------------------------------------------------------------
2198
Ruben Brunk99e69712015-05-26 17:25:07 -07002199CameraService::CameraClientManager::CameraClientManager() {
2200 setListener(std::make_shared<ClientEventListener>());
2201}
2202
Ruben Brunkcc776712015-02-17 20:18:47 -08002203CameraService::CameraClientManager::~CameraClientManager() {}
2204
2205sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2206 const String8& id) const {
2207 auto descriptor = get(id);
2208 if (descriptor == nullptr) {
2209 return sp<BasicClient>{nullptr};
2210 }
2211 return descriptor->getValue();
2212}
2213
2214String8 CameraService::CameraClientManager::toString() const {
2215 auto all = getAll();
2216 String8 ret("[");
2217 bool hasAny = false;
2218 for (auto& i : all) {
2219 hasAny = true;
2220 String8 key = i->getKey();
2221 int32_t cost = i->getCost();
2222 int32_t pid = i->getOwnerId();
2223 int32_t priority = i->getPriority();
2224 auto conflicting = i->getConflicting();
2225 auto clientSp = i->getValue();
2226 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002227 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002228 if (clientSp.get() != nullptr) {
2229 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002230 uid_t clientUid = clientSp->getClientUid();
2231 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002232 }
2233 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2234 PRId32 ", ", key.string(), cost, pid, priority);
2235
Ruben Brunk6267b532015-04-30 17:44:07 -07002236 if (clientSp.get() != nullptr) {
2237 ret.appendFormat("User Id: %d, ", clientUserId);
2238 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002239 if (packageName.size() != 0) {
2240 ret.appendFormat("Client Package Name: %s", packageName.string());
2241 }
2242
2243 ret.append(", Conflicting Client Devices: {");
2244 for (auto& j : conflicting) {
2245 ret.appendFormat("%s, ", j.string());
2246 }
2247 ret.append("})");
2248 }
2249 if (hasAny) ret.append("\n");
2250 ret.append("]\n");
2251 return ret;
2252}
2253
2254CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2255 const String8& key, const sp<BasicClient>& value, int32_t cost,
2256 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2257
2258 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2259 key, value, cost, conflictingKeys, priority, ownerId);
2260}
2261
2262CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2263 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2264 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2265 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2266}
2267
2268// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269
2270static const int kDumpLockRetries = 50;
2271static const int kDumpLockSleep = 60000;
2272
2273static bool tryLock(Mutex& mutex)
2274{
2275 bool locked = false;
2276 for (int i = 0; i < kDumpLockRetries; ++i) {
2277 if (mutex.tryLock() == NO_ERROR) {
2278 locked = true;
2279 break;
2280 }
2281 usleep(kDumpLockSleep);
2282 }
2283 return locked;
2284}
2285
2286status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002287 ATRACE_CALL();
2288
Ruben Brunka8ca9152015-04-07 14:23:40 -07002289 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002291 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 "can't dump CameraService from pid=%d, uid=%d\n",
2293 getCallingPid(),
2294 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 write(fd, result.string(), result.size());
2296 } else {
2297 bool locked = tryLock(mServiceLock);
2298 // failed to lock - CameraService is probably deadlocked
2299 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002300 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002301 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 }
2303
2304 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002305 if (!mModule) {
2306 result = String8::format("No camera module available!\n");
2307 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002308
2309 // Dump event log for error information
2310 dumpEventLog(fd);
2311
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002312 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002313 return NO_ERROR;
2314 }
2315
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002316 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2317 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2318 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2319 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002320 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
Eino-Ville Talvala49c97052016-01-12 14:29:40 -08002321 result.appendFormat("Number of normal camera devices: %d\n", mNumberOfNormalCameras);
Ruben Brunkcc776712015-02-17 20:18:47 -08002322 String8 activeClientString = mActiveClientManager.toString();
2323 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002324 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002325
Ruben Brunkf81648e2014-04-17 16:14:57 -07002326 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2327 if (desc == NULL) {
2328 result.appendFormat("Vendor tags left unimplemented.\n");
2329 } else {
2330 result.appendFormat("Vendor tag definitions:\n");
2331 }
2332
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002333 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002334
2335 if (desc != NULL) {
2336 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2337 }
2338
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002339 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002340
2341 bool stateLocked = tryLock(mCameraStatesLock);
2342 if (!stateLocked) {
2343 result = String8::format("CameraStates in use, may be deadlocked\n");
2344 write(fd, result.string(), result.size());
2345 }
2346
2347 for (auto& state : mCameraStates) {
2348 String8 cameraId = state.first;
2349 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002350 camera_info info;
2351
Ruben Brunkcc776712015-02-17 20:18:47 -08002352 // TODO: Change getCameraInfo + HAL to use String cameraIds
2353 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002354 if (rc != OK) {
2355 result.appendFormat(" Error reading static information!\n");
2356 write(fd, result.string(), result.size());
2357 } else {
2358 result.appendFormat(" Facing: %s\n",
2359 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2360 result.appendFormat(" Orientation: %d\n", info.orientation);
2361 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002362 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002363 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2364 } else {
2365 deviceVersion = info.device_version;
2366 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002367
2368 auto conflicting = state.second->getConflicting();
2369 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2370 result.appendFormat(" Conflicting Devices:");
2371 for (auto& id : conflicting) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002372 result.appendFormat(" %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002373 }
2374 if (conflicting.size() == 0) {
2375 result.appendFormat(" NONE");
2376 }
2377 result.appendFormat("\n");
2378
2379 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002380 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002381 result.appendFormat(" Device static metadata:\n");
2382 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002383 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002384 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002385 } else {
2386 write(fd, result.string(), result.size());
2387 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002388
2389 CameraParameters p = state.second->getShimParams();
2390 if (!p.isEmpty()) {
2391 result = String8::format(" Camera1 API shim is using parameters:\n ");
2392 write(fd, result.string(), result.size());
2393 p.dump(fd, args);
2394 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002395 }
2396
Ruben Brunkcc776712015-02-17 20:18:47 -08002397 auto clientDescriptor = mActiveClientManager.get(cameraId);
2398 if (clientDescriptor == nullptr) {
2399 result = String8::format(" Device %s is closed, no client instance\n",
2400 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002401 write(fd, result.string(), result.size());
2402 continue;
2403 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002405 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2406 cameraId.string());
2407 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2408 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2409
2410 auto client = clientDescriptor->getValue();
2411 result.appendFormat("Client package: %s\n",
2412 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002413 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002414
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002415 client->dumpClient(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002417
2418 if (stateLocked) mCameraStatesLock.unlock();
2419
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002421 result = String8::format("\nNo active camera clients yet.\n");
2422 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423 }
2424
2425 if (locked) mServiceLock.unlock();
2426
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002427 // Dump camera traces if there were any
2428 write(fd, "\n", 1);
2429 camera3::CameraTraces::dump(fd, args);
2430
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 // change logging level
2432 int n = args.size();
2433 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002434 String16 verboseOption("-v");
2435 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 String8 levelStr(args[i+1]);
2437 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002438 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002440 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 }
2442 }
2443 }
2444 return NO_ERROR;
2445}
2446
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002447void CameraService::dumpEventLog(int fd) {
2448 String8 result = String8("\nPrior client events (most recent at top):\n");
2449
2450 Mutex::Autolock l(mLogLock);
2451 for (const auto& msg : mEventLog) {
2452 result.appendFormat(" %s\n", msg.string());
2453 }
2454
2455 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2456 result.append(" ...\n");
2457 } else if (mEventLog.size() == 0) {
2458 result.append(" [no events yet]\n");
2459 }
2460 result.append("\n");
2461
2462 write(fd, result.string(), result.size());
2463}
2464
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002465void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002466 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002467 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2468 if (mTorchClientMap[i] == who) {
2469 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002470 String8 cameraId = mTorchClientMap.keyAt(i);
2471 status_t res = mFlashlight->setTorchMode(cameraId, false);
2472 if (res) {
2473 ALOGE("%s: torch client died but couldn't turn off torch: "
2474 "%s (%d)", __FUNCTION__, strerror(-res), res);
2475 return;
2476 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002477 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002478 break;
2479 }
2480 }
2481}
2482
Ruben Brunkcc776712015-02-17 20:18:47 -08002483/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002484
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002485 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002486 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2487 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002488 */
2489
Ruben Brunka8ca9152015-04-07 14:23:40 -07002490 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2491
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002492 // check torch client
2493 handleTorchClientBinderDied(who);
2494
2495 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002496 if(!evictClientIdByRemote(who)) {
2497 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002498 return;
2499 }
2500
Ruben Brunkcc776712015-02-17 20:18:47 -08002501 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2502 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002503}
2504
Ruben Brunkcc776712015-02-17 20:18:47 -08002505void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2506 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002507}
2508
Ruben Brunkcc776712015-02-17 20:18:47 -08002509void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2510 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2511 // Do not lock mServiceLock here or can get into a deadlock from
2512 // connect() -> disconnect -> updateStatus
2513
2514 auto state = getCameraState(cameraId);
2515
2516 if (state == nullptr) {
2517 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2518 cameraId.string());
2519 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002520 }
2521
Ruben Brunkcc776712015-02-17 20:18:47 -08002522 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2523 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2524 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2525 (const String8& cameraId, ICameraServiceListener::Status status) {
2526
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002527 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2528 // Update torch status if it has a flash unit.
2529 Mutex::Autolock al(mTorchStatusMutex);
2530 ICameraServiceListener::TorchStatus torchStatus;
2531 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2532 NAME_NOT_FOUND) {
2533 ICameraServiceListener::TorchStatus newTorchStatus =
2534 status == ICameraServiceListener::STATUS_PRESENT ?
2535 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2536 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2537 if (torchStatus != newTorchStatus) {
2538 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2539 }
2540 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002541 }
2542
2543 Mutex::Autolock lock(mStatusListenerLock);
2544
2545 for (auto& listener : mListenerList) {
2546 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2547 int id = cameraIdToInt(cameraId);
2548 if (id != -1) listener->onStatusChanged(status, id);
2549 }
2550 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002551}
2552
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002553void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2554 const String8& cameraId) {
2555 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2556 if (proxyBinder == nullptr) return;
2557 String16 id(cameraId);
2558 proxyBinder->notifyCameraState(id, newState);
2559}
2560
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002561status_t CameraService::getTorchStatusLocked(
2562 const String8& cameraId,
2563 ICameraServiceListener::TorchStatus *status) const {
2564 if (!status) {
2565 return BAD_VALUE;
2566 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002567 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2568 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002569 // invalid camera ID or the camera doesn't have a flash unit
2570 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002571 }
2572
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002573 *status = mTorchStatusMap.valueAt(index);
2574 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002575}
2576
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002577status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002578 ICameraServiceListener::TorchStatus status) {
2579 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2580 if (index == NAME_NOT_FOUND) {
2581 return BAD_VALUE;
2582 }
2583 ICameraServiceListener::TorchStatus& item =
2584 mTorchStatusMap.editValueAt(index);
2585 item = status;
2586
2587 return OK;
2588}
2589
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590}; // namespace android