blob: be66ef84e16111eb9777baa0a815cdbdfd4f44fb [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>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080049#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080050#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070051#include <system/camera_metadata.h>
52#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070055#include "api1/CameraClient.h"
56#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070058#include "utils/CameraTraces.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
60namespace android {
61
62// ----------------------------------------------------------------------------
63// Logging support -- this is for debugging only
64// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070065volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Steve Blockb8a80522011-12-20 16:23:08 +000067#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
70static void setLogLevel(int level) {
71 android_atomic_write(level, &gLogLevel);
72}
73
74// ----------------------------------------------------------------------------
75
Igor Murashkincba2c162013-03-20 15:56:31 -070076extern "C" {
77static void camera_device_status_change(
78 const struct camera_module_callbacks* callbacks,
79 int camera_id,
80 int new_status) {
81 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080082 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070083
Ruben Brunkcc776712015-02-17 20:18:47 -080084 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
85 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070086}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080087
88static void torch_mode_status_change(
89 const struct camera_module_callbacks* callbacks,
90 const char* camera_id,
91 int new_status) {
92 if (!callbacks || !camera_id) {
93 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
94 callbacks, camera_id);
95 }
96 sp<CameraService> cs = const_cast<CameraService*>(
97 static_cast<const CameraService*>(callbacks));
98
99 ICameraServiceListener::TorchStatus status;
100 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800101 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800102 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
103 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800104 case TORCH_MODE_STATUS_AVAILABLE_OFF:
105 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
106 break;
107 case TORCH_MODE_STATUS_AVAILABLE_ON:
108 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800109 break;
110 default:
111 ALOGE("Unknown torch status %d", new_status);
112 return;
113 }
114
115 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800116 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800117 status);
118}
Igor Murashkincba2c162013-03-20 15:56:31 -0700119} // extern "C"
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
123// This is ugly and only safe if we never re-create the CameraService, but
124// should be ok for now.
125static CameraService *gCameraService;
126
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800127CameraService::CameraService() :
128 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
129 mSoundRef(0), mModule(nullptr),
130 mNumberOfCameras(0), mNumberOfNormalCameras(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000131 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700132 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800133
Igor Murashkincba2c162013-03-20 15:56:31 -0700134 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800135 this->torch_mode_status_change = android::torch_mode_status_change;
136
Ruben Brunkcc776712015-02-17 20:18:47 -0800137 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700138}
139
Iliyan Malchev8951a972011-04-14 16:55:59 -0700140void CameraService::onFirstRef()
141{
Ruben Brunkcc776712015-02-17 20:18:47 -0800142 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800143
Iliyan Malchev8951a972011-04-14 16:55:59 -0700144 BnCameraService::onFirstRef();
145
Ruben Brunk99e69712015-05-26 17:25:07 -0700146 // Update battery life tracking if service is restarting
147 BatteryNotifier& notifier(BatteryNotifier::getInstance());
148 notifier.noteResetCamera();
149 notifier.noteResetFlashlight();
150
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800151 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700152 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
153 (const hw_module_t **)&rawModule);
154 if (err < 0) {
155 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
156 logServiceError("Could not load camera HAL module", err);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700157 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700158 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800159
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700161 err = mModule->init();
162 if (err != OK) {
163 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
164 strerror(-err));
165 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800166
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700167 delete mModule;
168 mModule = nullptr;
169 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700170 }
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700171 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700172
173 mNumberOfCameras = mModule->getNumberOfCameras();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700174 mNumberOfNormalCameras = mNumberOfCameras;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700175
Yin-Chia Yehd4a653a2015-10-14 11:05:44 -0700176 // Setup vendor tags before we call get_camera_info the first time
177 // because HAL might need to setup static vendor keys in get_camera_info
178 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
179 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
180 setUpVendorTags();
181 }
182
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700183 mFlashlight = new CameraFlashlight(*mModule, *this);
184 status_t res = mFlashlight->findFlashUnits();
185 if (res) {
186 // impossible because we haven't open any camera devices.
187 ALOGE("Failed to find flash units.");
188 }
189
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700190 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700191 for (int i = 0; i < mNumberOfCameras; i++) {
192 String8 cameraId = String8::format("%d", i);
193
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700194 // Get camera info
195
196 struct camera_info info;
197 bool haveInfo = true;
198 status_t rc = mModule->getCameraInfo(i, &info);
199 if (rc != NO_ERROR) {
200 ALOGE("%s: Received error loading camera info for device %d, cost and"
201 " conflicting devices fields set to defaults for this device.",
202 __FUNCTION__, i);
203 haveInfo = false;
204 }
205
206 // Check for backwards-compatibility support
207 if (haveInfo) {
208 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
209 delete mModule;
210 mModule = nullptr;
211 return;
212 }
213 }
214
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700215 // Defaults to use for cost and conflicting devices
216 int cost = 100;
217 char** conflicting_devices = nullptr;
218 size_t conflicting_devices_length = 0;
219
220 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700221 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
222 cost = info.resource_cost;
223 conflicting_devices = info.conflicting_devices;
224 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700225 }
226
227 std::set<String8> conflicting;
228 for (size_t i = 0; i < conflicting_devices_length; i++) {
229 conflicting.emplace(String8(conflicting_devices[i]));
230 }
231
232 // Initialize state for each camera device
233 {
234 Mutex::Autolock lock(mCameraStatesLock);
235 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
236 conflicting));
237 }
238
239 if (mFlashlight->hasFlashUnit(cameraId)) {
240 mTorchStatusMap.add(cameraId,
241 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
242 }
243 }
244
245 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
246 mModule->setCallbacks(this);
247 }
248
Ruben Brunk2823ce02015-05-19 17:25:13 -0700249 CameraService::pingCameraServiceProxy();
250}
251
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700252sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Ruben Brunk2823ce02015-05-19 17:25:13 -0700253 sp<IServiceManager> sm = defaultServiceManager();
254 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
255 if (binder == nullptr) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700256 return nullptr;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700257 }
258 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700259 return proxyBinder;
260}
261
262void CameraService::pingCameraServiceProxy() {
263 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
264 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700265 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700266}
267
Mathias Agopian65ab4712010-07-14 17:59:35 -0700268CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800269 if (mModule) {
270 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800271 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800272 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800273 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800274 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275}
276
Ruben Brunkcc776712015-02-17 20:18:47 -0800277void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
278 camera_device_status_t newStatus) {
279 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700280 cameraId, newStatus);
281
Ruben Brunkcc776712015-02-17 20:18:47 -0800282 String8 id = String8::format("%d", cameraId);
283 std::shared_ptr<CameraState> state = getCameraState(id);
284
285 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700286 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
287 return;
288 }
289
Ruben Brunkcc776712015-02-17 20:18:47 -0800290 ICameraServiceListener::Status oldStatus = state->getStatus();
291
292 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
293 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700294 return;
295 }
296
Igor Murashkincba2c162013-03-20 15:56:31 -0700297 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700298 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
299 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800300 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700301 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800302 // Don't do this in updateStatus to avoid deadlock over mServiceLock
303 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700304
Ruben Brunkcc776712015-02-17 20:18:47 -0800305 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
306 // to this device until the status changes
307 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700308
Ruben Brunkcc776712015-02-17 20:18:47 -0800309 // Remove cached shim parameters
310 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700311
Ruben Brunkcc776712015-02-17 20:18:47 -0800312 // Remove the client from the list of active clients
313 clientToDisconnect = removeClientLocked(id);
314
315 // Notify the client of disconnection
316 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
317 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700318 }
319
Ruben Brunkcc776712015-02-17 20:18:47 -0800320 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
321 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700322
Ruben Brunkcc776712015-02-17 20:18:47 -0800323 // Disconnect client
324 if (clientToDisconnect.get() != nullptr) {
325 // Ensure not in binder RPC so client disconnect PID checks work correctly
326 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
327 "onDeviceStatusChanged must be called from the camera service process!");
328 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700329 }
330
Ruben Brunkcc776712015-02-17 20:18:47 -0800331 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700332 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
333 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
334 newStatus));
335 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800336 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700337 }
338
Igor Murashkincba2c162013-03-20 15:56:31 -0700339}
340
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800341void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800342 ICameraServiceListener::TorchStatus newStatus) {
343 Mutex::Autolock al(mTorchStatusMutex);
344 onTorchStatusChangedLocked(cameraId, newStatus);
345}
346
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800347void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800348 ICameraServiceListener::TorchStatus newStatus) {
349 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
350 __FUNCTION__, cameraId.string(), newStatus);
351
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800352 ICameraServiceListener::TorchStatus status;
353 status_t res = getTorchStatusLocked(cameraId, &status);
354 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700355 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
356 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800357 return;
358 }
359 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800360 return;
361 }
362
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800363 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800364 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800365 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
366 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800367 return;
368 }
369
Ruben Brunkcc776712015-02-17 20:18:47 -0800370 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700371 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700372 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700373 auto iter = mTorchUidMap.find(cameraId);
374 if (iter != mTorchUidMap.end()) {
375 int oldUid = iter->second.second;
376 int newUid = iter->second.first;
377 BatteryNotifier& notifier(BatteryNotifier::getInstance());
378 if (oldUid != newUid) {
379 // If the UID has changed, log the status and update current UID in mTorchUidMap
380 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
381 notifier.noteFlashlightOff(cameraId, oldUid);
382 }
383 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
384 notifier.noteFlashlightOn(cameraId, newUid);
385 }
386 iter->second.second = newUid;
387 } else {
388 // If the UID has not changed, log the status
389 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
390 notifier.noteFlashlightOn(cameraId, oldUid);
391 } else {
392 notifier.noteFlashlightOff(cameraId, oldUid);
393 }
394 }
395 }
396 }
397
398 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800399 Mutex::Autolock lock(mStatusListenerLock);
400 for (auto& i : mListenerList) {
401 i->onTorchStatusChanged(newStatus, String16{cameraId});
402 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800403 }
404}
405
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700407 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700408 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
409}
410
411int32_t CameraService::getNumberOfCameras(int type) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700412 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700413 switch (type) {
414 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
415 return mNumberOfNormalCameras;
416 case CAMERA_TYPE_ALL:
417 return mNumberOfCameras;
418 default:
419 ALOGW("%s: Unknown camera type %d, returning 0",
420 __FUNCTION__, type);
421 return 0;
422 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700423}
424
425status_t CameraService::getCameraInfo(int cameraId,
426 struct CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700427 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700428 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700429 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700430 }
431
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
433 return BAD_VALUE;
434 }
435
Iliyan Malchev8951a972011-04-14 16:55:59 -0700436 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700437 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800438 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700439 cameraInfo->facing = info.facing;
440 cameraInfo->orientation = info.orientation;
441 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442}
443
Ruben Brunkcc776712015-02-17 20:18:47 -0800444int CameraService::cameraIdToInt(const String8& cameraId) {
445 errno = 0;
446 size_t pos = 0;
447 int ret = stoi(std::string{cameraId.string()}, &pos);
448 if (errno != 0 || pos != cameraId.size()) {
449 return -1;
450 }
451 return ret;
452}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700453
454status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700455 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700456 status_t ret = OK;
457 struct CameraInfo info;
458 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
459 return ret;
460 }
461
462 CameraMetadata shimInfo;
463 int32_t orientation = static_cast<int32_t>(info.orientation);
464 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
465 return ret;
466 }
467
468 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
469 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
470 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
471 return ret;
472 }
473
Igor Murashkin65d14b92014-06-17 12:03:20 -0700474 CameraParameters shimParams;
475 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
476 // Error logged by callee
477 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700478 }
479
480 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700481 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700482 Vector<int32_t> formats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700483 {
484 shimParams.getSupportedPreviewSizes(/*out*/sizes);
485 shimParams.getSupportedPreviewFormats(/*out*/formats);
486 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700487 }
488
489 // Always include IMPLEMENTATION_DEFINED
490 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
491
492 const size_t INTS_PER_CONFIG = 4;
493
494 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700495 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
496
497 Vector<int32_t> streamConfigs;
498 streamConfigs.setCapacity(streamConfigSize);
499
Ruben Brunkb2119af2014-05-09 19:57:56 -0700500 for (size_t i = 0; i < formats.size(); ++i) {
501 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700502 streamConfigs.add(formats[i]);
503 streamConfigs.add(sizes[j].width);
504 streamConfigs.add(sizes[j].height);
505 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700506 }
507 }
508
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700509 for (size_t i = 0; i < jpegSizes.size(); ++i) {
510 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
511 streamConfigs.add(jpegSizes[i].width);
512 streamConfigs.add(jpegSizes[i].height);
513 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
514 }
515
Ruben Brunkb2119af2014-05-09 19:57:56 -0700516 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700517 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700518 return ret;
519 }
520
521 int64_t fakeMinFrames[0];
522 // TODO: Fixme, don't fake min frame durations.
523 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
524 fakeMinFrames, 0)) != OK) {
525 return ret;
526 }
527
528 int64_t fakeStalls[0];
529 // TODO: Fixme, don't fake stall durations.
530 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
531 fakeStalls, 0)) != OK) {
532 return ret;
533 }
534
535 *cameraInfo = shimInfo;
536 return OK;
537}
538
Zhijun He2b59be82013-09-25 10:14:30 -0700539status_t CameraService::getCameraCharacteristics(int cameraId,
540 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700541 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700542 if (!cameraInfo) {
543 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
544 return BAD_VALUE;
545 }
546
547 if (!mModule) {
548 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
549 return -ENODEV;
550 }
551
Zhijun He2b59be82013-09-25 10:14:30 -0700552 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
553 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
554 return BAD_VALUE;
555 }
556
557 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700558 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800559 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800560 getDeviceVersion(cameraId, &facing) < CAMERA_DEVICE_API_VERSION_3_0) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700561 /**
562 * Backwards compatibility mode for old HALs:
563 * - Convert CameraInfo into static CameraMetadata properties.
564 * - Retrieve cached CameraParameters for this camera. If none exist,
565 * attempt to open CameraClient and retrieve the CameraParameters.
566 * - Convert cached CameraParameters into static CameraMetadata
567 * properties.
568 */
569 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700570
Ruben Brunkb2119af2014-05-09 19:57:56 -0700571 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
572 return ret;
573 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700574
Ruben Brunkb2119af2014-05-09 19:57:56 -0700575 } else {
576 /**
577 * Normal HAL 2.1+ codepath.
578 */
579 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800580 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700581 *cameraInfo = info.static_camera_characteristics;
582 }
Zhijun He2b59be82013-09-25 10:14:30 -0700583
584 return ret;
585}
586
Ruben Brunkcc776712015-02-17 20:18:47 -0800587int CameraService::getCallingPid() {
588 return IPCThreadState::self()->getCallingPid();
589}
590
591int CameraService::getCallingUid() {
592 return IPCThreadState::self()->getCallingUid();
593}
594
595String8 CameraService::getFormattedCurrentTime() {
596 time_t now = time(nullptr);
597 char formattedTime[64];
598 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
599 return String8(formattedTime);
600}
601
602int CameraService::getCameraPriorityFromProcState(int procState) {
603 // Find the priority for the camera usage based on the process state. Higher priority clients
604 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700605 if (procState < 0) {
606 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
607 procState);
608 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800609 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700610 // Treat sleeping TOP processes the same as regular TOP processes, for
611 // access priority. This is important for lock-screen camera launch scenarios
612 if (procState == PROCESS_STATE_TOP_SLEEPING) {
613 procState = PROCESS_STATE_TOP;
614 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700615 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800616}
617
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800618status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700619 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800620 if (!mModule) {
621 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
622 return -ENODEV;
623 }
624
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800625 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
626 return OK;
627}
628
Igor Murashkin634a5152013-02-20 17:15:11 -0800629int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700630 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800631 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800632 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800633 return -1;
634 }
635
636 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800637 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800638 deviceVersion = info.device_version;
639 } else {
640 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
641 }
642
643 if (facing) {
644 *facing = info.facing;
645 }
646
647 return deviceVersion;
648}
649
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700650status_t CameraService::filterGetInfoErrorCode(status_t err) {
651 switch(err) {
652 case NO_ERROR:
653 case -EINVAL:
654 return err;
655 default:
656 break;
657 }
658 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800659}
660
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800661bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700662 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800663 vendor_tag_ops_t vOps = vendor_tag_ops_t();
664
665 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800666 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800667 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
668 return false;
669 }
670
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800671 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800672
673 // Ensure all vendor operations are present
674 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
675 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
676 vOps.get_tag_type == NULL) {
677 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
678 , __FUNCTION__);
679 return false;
680 }
681
682 // Read all vendor tag definitions into a descriptor
683 sp<VendorTagDescriptor> desc;
684 status_t res;
685 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
686 != OK) {
687 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
688 "received error %s (%d). Camera clients will not be able to use"
689 "vendor tags", __FUNCTION__, strerror(res), res);
690 return false;
691 }
692
693 // Set the global descriptor to use with camera metadata
694 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
695 return true;
696}
697
Ruben Brunkcc776712015-02-17 20:18:47 -0800698status_t CameraService::makeClient(const sp<CameraService>& cameraService,
699 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
700 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
701 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
702 /*out*/sp<BasicClient>* client) {
703
704 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
705 int id = cameraIdToInt(cameraId);
706 if (id == -1) {
707 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
708 cameraId.string());
709 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700710 }
711
Ruben Brunkcc776712015-02-17 20:18:47 -0800712 if (halVersion < 0 || halVersion == deviceVersion) {
713 // Default path: HAL version is unspecified by caller, create CameraClient
714 // based on device version reported by the HAL.
715 switch(deviceVersion) {
716 case CAMERA_DEVICE_API_VERSION_1_0:
717 if (effectiveApiLevel == API_1) { // Camera1 API route
718 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
719 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
720 clientPid, clientUid, getpid(), legacyMode);
721 } else { // Camera2 API route
722 ALOGW("Camera using old HAL version: %d", deviceVersion);
723 return -EOPNOTSUPP;
724 }
725 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800726 case CAMERA_DEVICE_API_VERSION_3_0:
727 case CAMERA_DEVICE_API_VERSION_3_1:
728 case CAMERA_DEVICE_API_VERSION_3_2:
729 case CAMERA_DEVICE_API_VERSION_3_3:
730 if (effectiveApiLevel == API_1) { // Camera1 API route
731 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
732 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
733 clientPid, clientUid, servicePid, legacyMode);
734 } else { // Camera2 API route
735 sp<ICameraDeviceCallbacks> tmp =
736 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
737 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
738 facing, clientPid, clientUid, servicePid);
739 }
740 break;
741 default:
742 // Should not be reachable
743 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
744 return INVALID_OPERATION;
745 }
746 } else {
747 // A particular HAL version is requested by caller. Create CameraClient
748 // based on the requested HAL version.
749 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
750 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
751 // Only support higher HAL version device opened as HAL1.0 device.
752 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
753 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
754 clientPid, clientUid, servicePid, legacyMode);
755 } else {
756 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
757 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
758 " opened as HAL %x device", halVersion, deviceVersion,
759 CAMERA_DEVICE_API_VERSION_1_0);
760 return INVALID_OPERATION;
761 }
762 }
763 return NO_ERROR;
764}
765
Ruben Brunk6267b532015-04-30 17:44:07 -0700766String8 CameraService::toString(std::set<userid_t> intSet) {
767 String8 s("");
768 bool first = true;
769 for (userid_t i : intSet) {
770 if (first) {
771 s.appendFormat("%d", i);
772 first = false;
773 } else {
774 s.appendFormat(", %d", i);
775 }
776 }
777 return s;
778}
779
Ruben Brunkcc776712015-02-17 20:18:47 -0800780status_t CameraService::initializeShimMetadata(int cameraId) {
781 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700782
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800783 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800784 String8 id = String8::format("%d", cameraId);
785 status_t ret = NO_ERROR;
786 sp<Client> tmp = nullptr;
787 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800788 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid,
789 USE_CALLING_PID, API_1, false, true, tmp)) != NO_ERROR) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800790 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
791 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700792 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800793 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700794}
795
Igor Murashkin65d14b92014-06-17 12:03:20 -0700796status_t CameraService::getLegacyParametersLazy(int cameraId,
797 /*out*/
798 CameraParameters* parameters) {
799
800 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
801
802 status_t ret = 0;
803
804 if (parameters == NULL) {
805 ALOGE("%s: parameters must not be null", __FUNCTION__);
806 return BAD_VALUE;
807 }
808
Ruben Brunkcc776712015-02-17 20:18:47 -0800809 String8 id = String8::format("%d", cameraId);
810
811 // Check if we already have parameters
812 {
813 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700814 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800815 auto cameraState = getCameraState(id);
816 if (cameraState == nullptr) {
817 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
818 return BAD_VALUE;
819 }
820 CameraParameters p = cameraState->getShimParams();
821 if (!p.isEmpty()) {
822 *parameters = p;
823 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700824 }
825 }
826
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 int64_t token = IPCThreadState::self()->clearCallingIdentity();
828 ret = initializeShimMetadata(cameraId);
829 IPCThreadState::self()->restoreCallingIdentity(token);
830 if (ret != NO_ERROR) {
831 // Error already logged by callee
832 return ret;
833 }
834
835 // Check for parameters again
836 {
837 // Scope for service lock
838 Mutex::Autolock lock(mServiceLock);
839 auto cameraState = getCameraState(id);
840 if (cameraState == nullptr) {
841 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
842 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700843 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800844 CameraParameters p = cameraState->getShimParams();
845 if (!p.isEmpty()) {
846 *parameters = p;
847 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700848 }
849 }
850
Ruben Brunkcc776712015-02-17 20:18:47 -0800851 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
852 __FUNCTION__);
853 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700854}
855
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800856// Can camera service trust the caller based on the calling UID?
857static bool isTrustedCallingUid(uid_t uid) {
858 switch (uid) {
859 case AID_MEDIA: // mediaserver
860 case AID_CAMERASERVER: // cameraserver
861 return true;
862 default:
863 return false;
864 }
865}
866
867status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid,
868 /*inout*/int& clientPid) const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800869
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 int callingPid = getCallingPid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800871 int callingUid = getCallingUid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500872
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800873 // Check if we can trust clientUid
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800874 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800875 clientUid = callingUid;
876 } else if (!isTrustedCallingUid(callingUid)) {
877 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
878 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
879 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800880 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800882 // Check if we can trust clientPid
883 if (clientPid == USE_CALLING_PID) {
884 clientPid = callingPid;
885 } else if (!isTrustedCallingUid(callingUid)) {
886 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
887 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
888 return PERMISSION_DENIED;
889 }
890
891 // If it's not calling from cameraserver, check the permission.
892 if (callingPid != getpid() &&
893 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
894 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
895 return PERMISSION_DENIED;
896 }
897
898 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
899 // connected to camera service directly.
900 clientPid = callingPid;
901
Iliyan Malchev8951a972011-04-14 16:55:59 -0700902 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800903 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
904 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700905 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700906 }
907
Ruben Brunkcc776712015-02-17 20:18:47 -0800908 if (getCameraState(cameraId) == nullptr) {
909 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
910 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700911 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 }
913
Ruben Brunk6267b532015-04-30 17:44:07 -0700914 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800915
Ruben Brunka8ca9152015-04-07 14:23:40 -0700916 // Only allow clients who are being used by the current foreground device user, unless calling
917 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700918 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
919 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
920 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
921 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700922 return PERMISSION_DENIED;
923 }
924
Ruben Brunkcc776712015-02-17 20:18:47 -0800925 return checkIfDeviceIsUsable(cameraId);
926}
927
928status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
929 auto cameraState = getCameraState(cameraId);
930 int callingPid = getCallingPid();
931 if (cameraState == nullptr) {
932 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
933 cameraId.string());
934 return -ENODEV;
935 }
936
937 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700938 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800939 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
940 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700941 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700942 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800943 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
944 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700945 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700946 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700947
Ruben Brunkcc776712015-02-17 20:18:47 -0800948 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800949}
950
Ruben Brunkcc776712015-02-17 20:18:47 -0800951void CameraService::finishConnectLocked(const sp<BasicClient>& client,
952 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800953
Ruben Brunkcc776712015-02-17 20:18:47 -0800954 // Make a descriptor for the incoming client
955 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
956 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
957
958 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
959 String8(client->getPackageName()));
960
961 if (evicted.size() > 0) {
962 // This should never happen - clients should already have been removed in disconnect
963 for (auto& i : evicted) {
964 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
965 __FUNCTION__, i->getKey().string());
966 }
967
968 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
969 __FUNCTION__);
970 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700971
972 // And register a death notification for the client callback. Do
973 // this last to avoid Binder policy where a nested Binder
974 // transaction might be pre-empted to service the client death
975 // notification if the client process dies before linkToDeath is
976 // invoked.
977 sp<IBinder> remoteCallback = client->getRemote();
978 if (remoteCallback != nullptr) {
979 remoteCallback->linkToDeath(this);
980 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800981}
982
983status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
984 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
985 /*out*/
986 sp<BasicClient>* client,
987 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700988 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800989 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700990 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 DescriptorPtr clientDescriptor;
992 {
993 if (effectiveApiLevel == API_1) {
994 // If we are using API1, any existing client for this camera ID with the same remote
995 // should be returned rather than evicted to allow MediaRecorder to work properly.
996
997 auto current = mActiveClientManager.get(cameraId);
998 if (current != nullptr) {
999 auto clientSp = current->getValue();
1000 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001001 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1002 ALOGW("CameraService connect called from same client, but with a different"
1003 " API level, evicting prior client...");
1004 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001006 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001007 *client = clientSp;
1008 return NO_ERROR;
1009 }
1010 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001011 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001012 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001013
Ruben Brunkcc776712015-02-17 20:18:47 -08001014 // Return error if the device was unplugged or removed by the HAL for some reason
1015 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1016 return ret;
1017 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001018
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 // Get current active client PIDs
1020 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1021 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001022
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001023 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1024 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1025 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1026 // not have an out-of-class definition.
1027 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001028
Ruben Brunkcc776712015-02-17 20:18:47 -08001029 // Get priorites of all active PIDs
1030 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1031 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001032
Ruben Brunkcc776712015-02-17 20:18:47 -08001033 // Update all active clients' priorities
1034 std::map<int,int> pidToPriorityMap;
1035 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1036 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1037 }
1038 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001039
Ruben Brunkcc776712015-02-17 20:18:47 -08001040 // Get state for the given cameraId
1041 auto state = getCameraState(cameraId);
1042 if (state == nullptr) {
1043 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1044 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001045 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001046 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001047
1048 // Make descriptor for incoming client
1049 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1050 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1051 state->getConflicting(),
1052 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1053
1054 // Find clients that would be evicted
1055 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1056
1057 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1058 // background, so we cannot do evictions
1059 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1060 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1061 " priority).", clientPid);
1062
1063 sp<BasicClient> clientSp = clientDescriptor->getValue();
1064 String8 curTime = getFormattedCurrentTime();
1065 auto incompatibleClients =
1066 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1067
1068 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001069 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001070 cameraId.string(), packageName.string(), clientPid,
1071 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1072
1073 for (auto& i : incompatibleClients) {
1074 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1075 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1076 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1077 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001078 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1079 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1080 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1081 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001082 }
1083
1084 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001085 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001086 mEventLog.add(msg);
1087
1088 return -EBUSY;
1089 }
1090
1091 for (auto& i : evicted) {
1092 sp<BasicClient> clientSp = i->getValue();
1093 if (clientSp.get() == nullptr) {
1094 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1095
1096 // TODO: Remove this
1097 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1098 __FUNCTION__);
1099 mActiveClientManager.remove(i);
1100 continue;
1101 }
1102
1103 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1104 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001105 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001106
Ruben Brunkcc776712015-02-17 20:18:47 -08001107 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001108 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1109 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1110 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001111 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1112 i->getOwnerId(), i->getPriority(), cameraId.string(),
1113 packageName.string(), clientPid,
1114 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1115
1116 // Notify the client of disconnection
1117 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1118 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001119 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001120 }
1121
Ruben Brunkcc776712015-02-17 20:18:47 -08001122 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1123 // other clients from connecting in mServiceLockWrapper if held
1124 mServiceLock.unlock();
1125
1126 // Clear caller identity temporarily so client disconnect PID checks work correctly
1127 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1128
1129 // Destroy evicted clients
1130 for (auto& i : evictedClients) {
1131 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001132 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001133 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001134
1135 IPCThreadState::self()->restoreCallingIdentity(token);
1136
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001137 for (const auto& i : evictedClients) {
1138 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1139 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1140 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1141 if (ret == TIMED_OUT) {
1142 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1143 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1144 mActiveClientManager.toString().string());
1145 return -EBUSY;
1146 }
1147 if (ret != NO_ERROR) {
1148 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1149 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1150 ret, mActiveClientManager.toString().string());
1151 return ret;
1152 }
1153 }
1154
1155 evictedClients.clear();
1156
Ruben Brunkcc776712015-02-17 20:18:47 -08001157 // Once clients have been disconnected, relock
1158 mServiceLock.lock();
1159
1160 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1161 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1162 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001163 }
1164
Ruben Brunkcc776712015-02-17 20:18:47 -08001165 *partial = clientDescriptor;
1166 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001167}
1168
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001169status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001170 const sp<ICameraClient>& cameraClient,
1171 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001172 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001173 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001174 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001175 /*out*/
1176 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001177
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001178 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001179 status_t ret = NO_ERROR;
1180 String8 id = String8::format("%d", cameraId);
1181 sp<Client> client = nullptr;
1182 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001183 clientPackageName, clientUid, clientPid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001184
Ruben Brunkcc776712015-02-17 20:18:47 -08001185 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001186 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001187 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001188 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }
1190
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001191 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001192 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193}
1194
Zhijun Heb10cdad2014-06-16 16:38:35 -07001195status_t CameraService::connectLegacy(
1196 const sp<ICameraClient>& cameraClient,
1197 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001198 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001199 int clientUid,
1200 /*out*/
1201 sp<ICamera>& device) {
1202
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001203 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001204 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001205 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001206 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001207 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001208 /*
1209 * Either the HAL version is unspecified in which case this just creates
1210 * a camera client selected by the latest device version, or
1211 * it's a particular version in which case the HAL must supported
1212 * the open_legacy call
1213 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001214 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001215 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001216 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001217 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001218 return INVALID_OPERATION;
1219 }
1220
Ruben Brunkcc776712015-02-17 20:18:47 -08001221 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001222 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001223 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001224 clientUid, USE_CALLING_PID, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001225
Ruben Brunkcc776712015-02-17 20:18:47 -08001226 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001227 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001228 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001229 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001230 }
1231
Zhijun Heb10cdad2014-06-16 16:38:35 -07001232 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001234}
1235
Ruben Brunkcc776712015-02-17 20:18:47 -08001236status_t CameraService::connectDevice(
1237 const sp<ICameraDeviceCallbacks>& cameraCb,
1238 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001239 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001240 int clientUid,
1241 /*out*/
1242 sp<ICameraDeviceUser>& device) {
1243
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001244 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001245 status_t ret = NO_ERROR;
1246 String8 id = String8::format("%d", cameraId);
1247 sp<CameraDeviceClient> client = nullptr;
1248 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001249 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, USE_CALLING_PID,
1250 API_2, false, false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001251
1252 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001253 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001254 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001255 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001256 }
1257
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 device = client;
1259 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001260}
1261
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001262status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1263 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001264
1265 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001266 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001267 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001268 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001269 }
1270
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001271 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001272 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001273
1274 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001275 auto state = getCameraState(id);
1276 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001277 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001278 return -EINVAL;
1279 }
1280
1281 ICameraServiceListener::Status cameraStatus = state->getStatus();
1282 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1283 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001284 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001285 return -EINVAL;
1286 }
1287
1288 {
1289 Mutex::Autolock al(mTorchStatusMutex);
1290 ICameraServiceListener::TorchStatus status;
1291 status_t res = getTorchStatusLocked(id, &status);
1292 if (res) {
1293 ALOGE("%s: getting current torch status failed for camera %s",
1294 __FUNCTION__, id.string());
1295 return -EINVAL;
1296 }
1297
1298 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001300 ALOGE("%s: torch mode of camera %s is not available because "
1301 "camera is in use", __FUNCTION__, id.string());
1302 return -EBUSY;
1303 } else {
1304 ALOGE("%s: torch mode of camera %s is not available due to "
1305 "insufficient resources", __FUNCTION__, id.string());
1306 return -EUSERS;
1307 }
1308 }
1309 }
1310
Ruben Brunk99e69712015-05-26 17:25:07 -07001311 {
1312 // Update UID map - this is used in the torch status changed callbacks, so must be done
1313 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001314 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001315 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1316 mTorchUidMap[id].first = uid;
1317 mTorchUidMap[id].second = uid;
1318 } else {
1319 // Set the pending UID
1320 mTorchUidMap[id].first = uid;
1321 }
1322 }
1323
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001324 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001325
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001326 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001327 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1328 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001329 return res;
1330 }
1331
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001332 {
1333 // update the link to client's death
1334 Mutex::Autolock al(mTorchClientMapMutex);
1335 ssize_t index = mTorchClientMap.indexOfKey(id);
1336 if (enabled) {
1337 if (index == NAME_NOT_FOUND) {
1338 mTorchClientMap.add(id, clientBinder);
1339 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001340 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001341 mTorchClientMap.replaceValueAt(index, clientBinder);
1342 }
1343 clientBinder->linkToDeath(this);
1344 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001345 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001346 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001347 }
1348
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001349 return OK;
1350}
1351
Ruben Brunk6267b532015-04-30 17:44:07 -07001352void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001353 ATRACE_CALL();
1354
Ruben Brunk36597b22015-03-20 22:15:57 -07001355 switch(eventId) {
1356 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001357 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001358 break;
1359 }
1360 case ICameraService::NO_EVENT:
1361 default: {
1362 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1363 eventId);
1364 break;
1365 }
1366 }
1367}
1368
Ruben Brunk99e69712015-05-26 17:25:07 -07001369status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001370 ATRACE_CALL();
1371
Igor Murashkinbfc99152013-02-27 12:55:20 -08001372 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001373
Ruben Brunk3450ba72015-06-16 11:00:37 -07001374 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001375 ALOGE("%s: Listener must not be null", __FUNCTION__);
1376 return BAD_VALUE;
1377 }
1378
Igor Murashkinbfc99152013-02-27 12:55:20 -08001379 Mutex::Autolock lock(mServiceLock);
1380
Ruben Brunkcc776712015-02-17 20:18:47 -08001381 {
1382 Mutex::Autolock lock(mStatusListenerLock);
1383 for (auto& it : mListenerList) {
1384 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1385 ALOGW("%s: Tried to add listener %p which was already subscribed",
1386 __FUNCTION__, listener.get());
1387 return ALREADY_EXISTS;
1388 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001389 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001390
1391 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001392 }
1393
Igor Murashkinbfc99152013-02-27 12:55:20 -08001394
Igor Murashkincba2c162013-03-20 15:56:31 -07001395 /* Immediately signal current status to this listener only */
1396 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001397 Mutex::Autolock lock(mCameraStatesLock);
1398 for (auto& i : mCameraStates) {
1399 // TODO: Update binder to use String16 for camera IDs and remove;
1400 int id = cameraIdToInt(i.first);
1401 if (id == -1) continue;
1402
1403 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001404 }
1405 }
1406
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001407 /* Immediately signal current torch status to this listener only */
1408 {
1409 Mutex::Autolock al(mTorchStatusMutex);
1410 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001411 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1412 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001413 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001414 }
1415
Igor Murashkinbfc99152013-02-27 12:55:20 -08001416 return OK;
1417}
Ruben Brunkcc776712015-02-17 20:18:47 -08001418
1419status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001420 ATRACE_CALL();
1421
Igor Murashkinbfc99152013-02-27 12:55:20 -08001422 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1423
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001424 if (listener == 0) {
1425 ALOGE("%s: Listener must not be null", __FUNCTION__);
1426 return BAD_VALUE;
1427 }
1428
Igor Murashkinbfc99152013-02-27 12:55:20 -08001429 Mutex::Autolock lock(mServiceLock);
1430
Ruben Brunkcc776712015-02-17 20:18:47 -08001431 {
1432 Mutex::Autolock lock(mStatusListenerLock);
1433 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1434 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1435 mListenerList.erase(it);
1436 return OK;
1437 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001438 }
1439 }
1440
1441 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1442 __FUNCTION__, listener.get());
1443
1444 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001445}
1446
Ruben Brunkcc776712015-02-17 20:18:47 -08001447status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001448
1449 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001450 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1451
1452 if (parameters == NULL) {
1453 ALOGE("%s: parameters must not be null", __FUNCTION__);
1454 return BAD_VALUE;
1455 }
1456
1457 status_t ret = 0;
1458
1459 CameraParameters shimParams;
1460 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1461 // Error logged by caller
1462 return ret;
1463 }
1464
1465 String8 shimParamsString8 = shimParams.flatten();
1466 String16 shimParamsString16 = String16(shimParamsString8);
1467
1468 *parameters = shimParamsString16;
1469
1470 return OK;
1471}
1472
1473status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001474 ATRACE_CALL();
1475
Igor Murashkin65d14b92014-06-17 12:03:20 -07001476 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1477
1478 switch (apiVersion) {
1479 case API_VERSION_1:
1480 case API_VERSION_2:
1481 break;
1482 default:
1483 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1484 return BAD_VALUE;
1485 }
1486
1487 int facing = -1;
1488 int deviceVersion = getDeviceVersion(cameraId, &facing);
1489
1490 switch(deviceVersion) {
1491 case CAMERA_DEVICE_API_VERSION_1_0:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001492 case CAMERA_DEVICE_API_VERSION_3_0:
1493 case CAMERA_DEVICE_API_VERSION_3_1:
1494 if (apiVersion == API_VERSION_2) {
1495 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1496 __FUNCTION__, cameraId);
1497 return -EOPNOTSUPP;
1498 } else { // if (apiVersion == API_VERSION_1) {
1499 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1500 __FUNCTION__, cameraId);
1501 return OK;
1502 }
1503 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001504 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001505 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1506 __FUNCTION__, cameraId);
1507 return OK;
1508 case -1:
1509 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1510 return BAD_VALUE;
1511 default:
1512 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1513 return INVALID_OPERATION;
1514 }
1515
1516 return OK;
1517}
1518
Ruben Brunkcc776712015-02-17 20:18:47 -08001519void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001520 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 for (auto& i : mActiveClientManager.getAll()) {
1522 auto clientSp = i->getValue();
1523 if (clientSp.get() == client) {
1524 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001525 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001526 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001527}
1528
Ruben Brunkcc776712015-02-17 20:18:47 -08001529bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1530 const int callingPid = getCallingPid();
1531 const int servicePid = getpid();
1532 bool ret = false;
1533 {
1534 // Acquire mServiceLock and prevent other clients from connecting
1535 std::unique_ptr<AutoConditionLock> lock =
1536 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001537
Igor Murashkin634a5152013-02-20 17:15:11 -08001538
Ruben Brunkcc776712015-02-17 20:18:47 -08001539 std::vector<sp<BasicClient>> evicted;
1540 for (auto& i : mActiveClientManager.getAll()) {
1541 auto clientSp = i->getValue();
1542 if (clientSp.get() == nullptr) {
1543 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1544 mActiveClientManager.remove(i);
1545 continue;
1546 }
1547 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1548 callingPid == clientSp->getClientPid())) {
1549 mActiveClientManager.remove(i);
1550 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001551
Ruben Brunkcc776712015-02-17 20:18:47 -08001552 // Notify the client of disconnection
1553 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1554 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001555 }
1556 }
1557
Ruben Brunkcc776712015-02-17 20:18:47 -08001558 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1559 // other clients from connecting in mServiceLockWrapper if held
1560 mServiceLock.unlock();
1561
Ruben Brunk36597b22015-03-20 22:15:57 -07001562 // Do not clear caller identity, remote caller should be client proccess
1563
Ruben Brunkcc776712015-02-17 20:18:47 -08001564 for (auto& i : evicted) {
1565 if (i.get() != nullptr) {
1566 i->disconnect();
1567 ret = true;
1568 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001569 }
1570
Ruben Brunkcc776712015-02-17 20:18:47 -08001571 // Reacquire mServiceLock
1572 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001573
Ruben Brunkcc776712015-02-17 20:18:47 -08001574 } // lock is destroyed, allow further connect calls
1575
1576 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001577}
1578
Igor Murashkinecf17e82012-10-02 16:05:11 -07001579
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001580/**
1581 * Check camera capabilities, such as support for basic color operation
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001582 * Also check that the device HAL version is still in support
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001583 */
1584int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
Yin-Chia Yeh654b4bf2015-12-08 12:19:31 -08001585 // device_version undefined in CAMERA_MODULE_API_VERSION_1_0,
1586 // All CAMERA_MODULE_API_VERSION_1_0 devices are backward-compatible
1587 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
1588 // Verify the device version is in the supported range
1589 switch (info.device_version) {
1590 case CAMERA_DEVICE_API_VERSION_1_0:
1591 case CAMERA_DEVICE_API_VERSION_3_0:
1592 case CAMERA_DEVICE_API_VERSION_3_1:
1593 case CAMERA_DEVICE_API_VERSION_3_2:
1594 case CAMERA_DEVICE_API_VERSION_3_3:
1595 // in support
1596 break;
1597 case CAMERA_DEVICE_API_VERSION_2_0:
1598 case CAMERA_DEVICE_API_VERSION_2_1:
1599 // no longer supported
1600 default:
1601 ALOGE("%s: Device %d has HAL version %x, which is not supported",
1602 __FUNCTION__, id, info.device_version);
1603 String8 msg = String8::format(
1604 "Unsupported device HAL version %x for device %d",
1605 info.device_version, id);
1606 logServiceError(msg.string(), NO_INIT);
1607 return NO_INIT;
1608 }
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001609 }
1610
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001611 // Assume all devices pre-v3.3 are backward-compatible
1612 bool isBackwardCompatible = true;
1613 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1614 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1615 isBackwardCompatible = false;
1616 status_t res;
1617 camera_metadata_ro_entry_t caps;
1618 res = find_camera_metadata_ro_entry(
1619 info.static_camera_characteristics,
1620 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1621 &caps);
1622 if (res != 0) {
1623 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1624 __FUNCTION__, id);
1625 caps.count = 0;
1626 }
1627 for (size_t i = 0; i < caps.count; i++) {
1628 if (caps.data.u8[i] ==
1629 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1630 isBackwardCompatible = true;
1631 break;
1632 }
1633 }
1634 }
1635
1636 if (!isBackwardCompatible) {
1637 mNumberOfNormalCameras--;
1638 *latestStrangeCameraId = id;
1639 } else {
1640 if (id > *latestStrangeCameraId) {
1641 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1642 "This is not allowed due backward-compatibility requirements",
1643 __FUNCTION__, id, *latestStrangeCameraId);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001644 logServiceError("Invalid order of camera devices", NO_INIT);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001645 mNumberOfCameras = 0;
1646 mNumberOfNormalCameras = 0;
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001647 return NO_INIT;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001648 }
1649 }
1650 return OK;
1651}
1652
Ruben Brunkcc776712015-02-17 20:18:47 -08001653std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1654 const String8& cameraId) const {
1655 std::shared_ptr<CameraState> state;
1656 {
1657 Mutex::Autolock lock(mCameraStatesLock);
1658 auto iter = mCameraStates.find(cameraId);
1659 if (iter != mCameraStates.end()) {
1660 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 }
1662 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001663 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664}
1665
Ruben Brunkcc776712015-02-17 20:18:47 -08001666sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1667 // Remove from active clients list
1668 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1669 if (clientDescriptorPtr == nullptr) {
1670 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1671 cameraId.string());
1672 return sp<BasicClient>{nullptr};
1673 }
1674
1675 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001676}
1677
Ruben Brunk6267b532015-04-30 17:44:07 -07001678void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001679 // Acquire mServiceLock and prevent other clients from connecting
1680 std::unique_ptr<AutoConditionLock> lock =
1681 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1682
Ruben Brunk6267b532015-04-30 17:44:07 -07001683 std::set<userid_t> newAllowedUsers;
1684 for (size_t i = 0; i < length; i++) {
1685 if (newUserId[i] < 0) {
1686 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1687 __FUNCTION__, newUserId[i]);
1688 return;
1689 }
1690 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001691 }
1692
Ruben Brunka8ca9152015-04-07 14:23:40 -07001693
Ruben Brunk6267b532015-04-30 17:44:07 -07001694 if (newAllowedUsers == mAllowedUsers) {
1695 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1696 return;
1697 }
1698
1699 logUserSwitch(mAllowedUsers, newAllowedUsers);
1700
1701 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001702
1703 // Current user has switched, evict all current clients.
1704 std::vector<sp<BasicClient>> evicted;
1705 for (auto& i : mActiveClientManager.getAll()) {
1706 auto clientSp = i->getValue();
1707
1708 if (clientSp.get() == nullptr) {
1709 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1710 continue;
1711 }
1712
Ruben Brunk6267b532015-04-30 17:44:07 -07001713 // Don't evict clients that are still allowed.
1714 uid_t clientUid = clientSp->getClientUid();
1715 userid_t clientUserId = multiuser_get_user_id(clientUid);
1716 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1717 continue;
1718 }
1719
Ruben Brunk36597b22015-03-20 22:15:57 -07001720 evicted.push_back(clientSp);
1721
1722 String8 curTime = getFormattedCurrentTime();
1723
1724 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1725 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001726
Ruben Brunk36597b22015-03-20 22:15:57 -07001727 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001728 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001729 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001730 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1731 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001732
1733 }
1734
1735 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1736 // blocking other clients from connecting in mServiceLockWrapper if held.
1737 mServiceLock.unlock();
1738
1739 // Clear caller identity temporarily so client disconnect PID checks work correctly
1740 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1741
1742 for (auto& i : evicted) {
1743 i->disconnect();
1744 }
1745
1746 IPCThreadState::self()->restoreCallingIdentity(token);
1747
1748 // Reacquire mServiceLock
1749 mServiceLock.lock();
1750}
Ruben Brunkcc776712015-02-17 20:18:47 -08001751
Ruben Brunka8ca9152015-04-07 14:23:40 -07001752void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001753 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001754 Mutex::Autolock l(mLogLock);
1755 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756}
1757
Ruben Brunka8ca9152015-04-07 14:23:40 -07001758void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001759 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001760 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001761 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001762 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001763}
1764
1765void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001766 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001767 // Log the clients evicted
1768 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001769 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001770}
1771
1772void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001773 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001774 // Log the client rejected
1775 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001776 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001777}
1778
Ruben Brunk6267b532015-04-30 17:44:07 -07001779void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1780 const std::set<userid_t>& newUserIds) {
1781 String8 newUsers = toString(newUserIds);
1782 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001783 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001784 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1785 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001786}
1787
1788void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1789 // Log the device removal
1790 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1791}
1792
1793void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1794 // Log the device removal
1795 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1796}
1797
1798void CameraService::logClientDied(int clientPid, const char* reason) {
1799 // Log the device removal
1800 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001801}
1802
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001803void CameraService::logServiceError(const char* msg, int errorCode) {
1804 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001805 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001806}
1807
Ruben Brunk36597b22015-03-20 22:15:57 -07001808status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1809 uint32_t flags) {
1810
1811 const int pid = getCallingPid();
1812 const int selfPid = getpid();
1813
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 // Permission checks
1815 switch (code) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001816 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1817 if (pid != selfPid) {
1818 // Ensure we're being called by system_server, or similar process with
1819 // permissions to notify the camera service about system events
1820 if (!checkCallingPermission(
1821 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1822 const int uid = getCallingUid();
1823 ALOGE("Permission Denial: cannot send updates to camera service about system"
1824 " events from pid=%d, uid=%d", pid, uid);
1825 return PERMISSION_DENIED;
1826 }
1827 }
1828 break;
1829 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830 }
1831
1832 return BnCameraService::onTransact(code, data, reply, flags);
1833}
1834
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835// We share the media players for shutter and recording sound for all clients.
1836// A reference count is kept to determine when we will actually release the
1837// media players.
1838
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001839MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001841 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001842 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 mp->prepare();
1844 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001845 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 return NULL;
1847 }
1848 return mp;
1849}
1850
1851void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001852 ATRACE_CALL();
1853
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 Mutex::Autolock lock(mSoundLock);
1855 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1856 if (mSoundRef++) return;
1857
1858 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001859 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1860 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
1863void CameraService::releaseSound() {
1864 Mutex::Autolock lock(mSoundLock);
1865 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1866 if (--mSoundRef) return;
1867
1868 for (int i = 0; i < NUM_SOUNDS; i++) {
1869 if (mSoundPlayer[i] != 0) {
1870 mSoundPlayer[i]->disconnect();
1871 mSoundPlayer[i].clear();
1872 }
1873 }
1874}
1875
1876void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001877 ATRACE_CALL();
1878
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 LOG1("playSound(%d)", kind);
1880 Mutex::Autolock lock(mSoundLock);
1881 sp<MediaPlayer> player = mSoundPlayer[kind];
1882 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001883 player->seekTo(0);
1884 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 }
1886}
1887
1888// ----------------------------------------------------------------------------
1889
1890CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001891 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001892 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001893 int cameraId, int cameraFacing,
1894 int clientPid, uid_t clientUid,
1895 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001896 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001897 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001898 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001899 cameraId, cameraFacing,
1900 clientPid, clientUid,
1901 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001902{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001904 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001906 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001909
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001910 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911}
1912
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913// tear down the client
1914CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001915 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001916 mDestructionStarted = true;
1917
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001918 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001919 // unconditionally disconnect. function is idempotent
1920 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921}
1922
Igor Murashkin634a5152013-02-20 17:15:11 -08001923CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001924 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001925 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001926 int cameraId, int cameraFacing,
1927 int clientPid, uid_t clientUid,
1928 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001929 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001930{
1931 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001932 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001933 mCameraId = cameraId;
1934 mCameraFacing = cameraFacing;
1935 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001936 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001937 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001938 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001939 mDestructionStarted = false;
1940}
1941
1942CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001943 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001944 mDestructionStarted = true;
1945}
1946
1947void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001948 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001949 return;
1950 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001951 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001952
1953 mCameraService->removeByClient(this);
1954 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001955 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001956
1957 sp<IBinder> remote = getRemote();
1958 if (remote != nullptr) {
1959 remote->unlinkToDeath(mCameraService);
1960 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001961
1962 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001963 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1964
Igor Murashkincba2c162013-03-20 15:56:31 -07001965 // client shouldn't be able to call into us anymore
1966 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001967}
1968
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08001969status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
1970 // No dumping of clients directly over Binder,
1971 // must go through CameraService::dump
1972 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
1973 IPCThreadState::self()->getCallingUid(), NULL, 0);
1974 return OK;
1975}
1976
Ruben Brunkcc776712015-02-17 20:18:47 -08001977String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001978 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001979}
1980
1981
1982int CameraService::BasicClient::getClientPid() const {
1983 return mClientPid;
1984}
1985
Ruben Brunk6267b532015-04-30 17:44:07 -07001986uid_t CameraService::BasicClient::getClientUid() const {
1987 return mClientUid;
1988}
1989
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001990bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1991 // Defaults to API2.
1992 return level == API_2;
1993}
1994
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001995status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001996 ATRACE_CALL();
1997
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001998 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001999 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002000 mOpsCallback = new OpsCallback(this);
2001
Igor Murashkine6800ce2013-03-04 17:25:57 -08002002 {
2003 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002004 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002005 }
2006
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002007 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002008 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002009 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002010 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002011
Svetoslav28e8ef72015-05-11 19:21:31 -07002012 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002013 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002014 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002015 return PERMISSION_DENIED;
2016 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002017
Svetoslav28e8ef72015-05-11 19:21:31 -07002018 if (res == AppOpsManager::MODE_IGNORED) {
2019 ALOGI("Camera %d: Access for \"%s\" has been restricted",
2020 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002021 // Return the same error as for device policy manager rejection
2022 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002023 }
2024
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002025 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002026
2027 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2028 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002029 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002030
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002031 // Transition device state to OPEN
2032 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2033 String8::format("%d", mCameraId));
2034
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002035 return OK;
2036}
2037
2038status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002039 ATRACE_CALL();
2040
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002041 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002042 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002043 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002044 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002045 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002046 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002047
Ruben Brunkcc776712015-02-17 20:18:47 -08002048 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2049 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002050
Ruben Brunkcc776712015-02-17 20:18:47 -08002051 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002052 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002053 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002054
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002055 // Transition device state to CLOSED
2056 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2057 String8::format("%d", mCameraId));
2058
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002059 // Notify flashlight that a camera device is closed.
2060 mCameraService->mFlashlight->deviceClosed(
2061 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002062 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002063 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002064 if (mOpsCallback != NULL) {
2065 mAppOpsManager.stopWatchingMode(mOpsCallback);
2066 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002067 mOpsCallback.clear();
2068
2069 return OK;
2070}
2071
2072void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002073 ATRACE_CALL();
2074
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002075 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002076 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002077
2078 if (op != AppOpsManager::OP_CAMERA) {
2079 ALOGW("Unexpected app ops notification received: %d", op);
2080 return;
2081 }
2082
2083 int32_t res;
2084 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002085 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002086 ALOGV("checkOp returns: %d, %s ", res,
2087 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2088 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2089 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2090 "UNKNOWN");
2091
2092 if (res != AppOpsManager::MODE_ALLOWED) {
2093 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2094 myName.string());
2095 // Reset the client PID to allow server-initiated disconnect,
2096 // and to prevent further calls by client.
2097 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002098 CaptureResultExtras resultExtras; // a dummy result (invalid)
2099 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002100 disconnect();
2101 }
2102}
2103
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104// ----------------------------------------------------------------------------
2105
Ruben Brunkcc776712015-02-17 20:18:47 -08002106// Provide client strong pointer for callbacks.
2107sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2108 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2109 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2110 if (clientDescriptor != nullptr) {
2111 return sp<Client>{
2112 static_cast<Client*>(clientDescriptor->getValue().get())};
2113 }
2114 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115}
2116
Jianing Weicb0652e2014-03-12 18:29:36 -07002117void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2118 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002119 (void) errorCode;
2120 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002121 if (mRemoteCallback != NULL) {
2122 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2123 } else {
2124 ALOGE("mRemoteCallback is NULL!!");
2125 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002126}
2127
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002128// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002129void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002130 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002131 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002132}
2133
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002134bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2135 return level == API_1;
2136}
2137
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002138CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2139 mClient(client) {
2140}
2141
2142void CameraService::Client::OpsCallback::opChanged(int32_t op,
2143 const String16& packageName) {
2144 sp<BasicClient> client = mClient.promote();
2145 if (client != NULL) {
2146 client->opChanged(op, packageName);
2147 }
2148}
2149
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002151// CameraState
2152// ----------------------------------------------------------------------------
2153
2154CameraService::CameraState::CameraState(const String8& id, int cost,
2155 const std::set<String8>& conflicting) : mId(id),
2156 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2157
2158CameraService::CameraState::~CameraState() {}
2159
2160ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2161 Mutex::Autolock lock(mStatusLock);
2162 return mStatus;
2163}
2164
2165CameraParameters CameraService::CameraState::getShimParams() const {
2166 return mShimParams;
2167}
2168
2169void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2170 mShimParams = params;
2171}
2172
2173int CameraService::CameraState::getCost() const {
2174 return mCost;
2175}
2176
2177std::set<String8> CameraService::CameraState::getConflicting() const {
2178 return mConflicting;
2179}
2180
2181String8 CameraService::CameraState::getId() const {
2182 return mId;
2183}
2184
2185// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002186// ClientEventListener
2187// ----------------------------------------------------------------------------
2188
2189void CameraService::ClientEventListener::onClientAdded(
2190 const resource_policy::ClientDescriptor<String8,
2191 sp<CameraService::BasicClient>>& descriptor) {
2192 auto basicClient = descriptor.getValue();
2193 if (basicClient.get() != nullptr) {
2194 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2195 notifier.noteStartCamera(descriptor.getKey(),
2196 static_cast<int>(basicClient->getClientUid()));
2197 }
2198}
2199
2200void CameraService::ClientEventListener::onClientRemoved(
2201 const resource_policy::ClientDescriptor<String8,
2202 sp<CameraService::BasicClient>>& descriptor) {
2203 auto basicClient = descriptor.getValue();
2204 if (basicClient.get() != nullptr) {
2205 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2206 notifier.noteStopCamera(descriptor.getKey(),
2207 static_cast<int>(basicClient->getClientUid()));
2208 }
2209}
2210
2211
2212// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002213// CameraClientManager
2214// ----------------------------------------------------------------------------
2215
Ruben Brunk99e69712015-05-26 17:25:07 -07002216CameraService::CameraClientManager::CameraClientManager() {
2217 setListener(std::make_shared<ClientEventListener>());
2218}
2219
Ruben Brunkcc776712015-02-17 20:18:47 -08002220CameraService::CameraClientManager::~CameraClientManager() {}
2221
2222sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2223 const String8& id) const {
2224 auto descriptor = get(id);
2225 if (descriptor == nullptr) {
2226 return sp<BasicClient>{nullptr};
2227 }
2228 return descriptor->getValue();
2229}
2230
2231String8 CameraService::CameraClientManager::toString() const {
2232 auto all = getAll();
2233 String8 ret("[");
2234 bool hasAny = false;
2235 for (auto& i : all) {
2236 hasAny = true;
2237 String8 key = i->getKey();
2238 int32_t cost = i->getCost();
2239 int32_t pid = i->getOwnerId();
2240 int32_t priority = i->getPriority();
2241 auto conflicting = i->getConflicting();
2242 auto clientSp = i->getValue();
2243 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002244 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 if (clientSp.get() != nullptr) {
2246 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002247 uid_t clientUid = clientSp->getClientUid();
2248 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002249 }
2250 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2251 PRId32 ", ", key.string(), cost, pid, priority);
2252
Ruben Brunk6267b532015-04-30 17:44:07 -07002253 if (clientSp.get() != nullptr) {
2254 ret.appendFormat("User Id: %d, ", clientUserId);
2255 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002256 if (packageName.size() != 0) {
2257 ret.appendFormat("Client Package Name: %s", packageName.string());
2258 }
2259
2260 ret.append(", Conflicting Client Devices: {");
2261 for (auto& j : conflicting) {
2262 ret.appendFormat("%s, ", j.string());
2263 }
2264 ret.append("})");
2265 }
2266 if (hasAny) ret.append("\n");
2267 ret.append("]\n");
2268 return ret;
2269}
2270
2271CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2272 const String8& key, const sp<BasicClient>& value, int32_t cost,
2273 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2274
2275 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2276 key, value, cost, conflictingKeys, priority, ownerId);
2277}
2278
2279CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2280 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2281 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2282 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2283}
2284
2285// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286
2287static const int kDumpLockRetries = 50;
2288static const int kDumpLockSleep = 60000;
2289
2290static bool tryLock(Mutex& mutex)
2291{
2292 bool locked = false;
2293 for (int i = 0; i < kDumpLockRetries; ++i) {
2294 if (mutex.tryLock() == NO_ERROR) {
2295 locked = true;
2296 break;
2297 }
2298 usleep(kDumpLockSleep);
2299 }
2300 return locked;
2301}
2302
2303status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002304 ATRACE_CALL();
2305
Ruben Brunka8ca9152015-04-07 14:23:40 -07002306 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002308 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309 "can't dump CameraService from pid=%d, uid=%d\n",
2310 getCallingPid(),
2311 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 write(fd, result.string(), result.size());
2313 } else {
2314 bool locked = tryLock(mServiceLock);
2315 // failed to lock - CameraService is probably deadlocked
2316 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002317 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002318 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319 }
2320
2321 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002322 if (!mModule) {
2323 result = String8::format("No camera module available!\n");
2324 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002325
2326 // Dump event log for error information
2327 dumpEventLog(fd);
2328
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002329 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002330 return NO_ERROR;
2331 }
2332
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002333 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2334 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2335 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2336 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002337 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
Eino-Ville Talvala49c97052016-01-12 14:29:40 -08002338 result.appendFormat("Number of normal camera devices: %d\n", mNumberOfNormalCameras);
Ruben Brunkcc776712015-02-17 20:18:47 -08002339 String8 activeClientString = mActiveClientManager.toString();
2340 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002341 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002342
Ruben Brunkf81648e2014-04-17 16:14:57 -07002343 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2344 if (desc == NULL) {
2345 result.appendFormat("Vendor tags left unimplemented.\n");
2346 } else {
2347 result.appendFormat("Vendor tag definitions:\n");
2348 }
2349
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002350 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002351
2352 if (desc != NULL) {
2353 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2354 }
2355
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002356 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002357
2358 bool stateLocked = tryLock(mCameraStatesLock);
2359 if (!stateLocked) {
2360 result = String8::format("CameraStates in use, may be deadlocked\n");
2361 write(fd, result.string(), result.size());
2362 }
2363
2364 for (auto& state : mCameraStates) {
2365 String8 cameraId = state.first;
2366 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002367 camera_info info;
2368
Ruben Brunkcc776712015-02-17 20:18:47 -08002369 // TODO: Change getCameraInfo + HAL to use String cameraIds
2370 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002371 if (rc != OK) {
2372 result.appendFormat(" Error reading static information!\n");
2373 write(fd, result.string(), result.size());
2374 } else {
2375 result.appendFormat(" Facing: %s\n",
2376 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2377 result.appendFormat(" Orientation: %d\n", info.orientation);
2378 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002379 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002380 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2381 } else {
2382 deviceVersion = info.device_version;
2383 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002384
2385 auto conflicting = state.second->getConflicting();
2386 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2387 result.appendFormat(" Conflicting Devices:");
2388 for (auto& id : conflicting) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002389 result.appendFormat(" %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002390 }
2391 if (conflicting.size() == 0) {
2392 result.appendFormat(" NONE");
2393 }
2394 result.appendFormat("\n");
2395
2396 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002397 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002398 result.appendFormat(" Device static metadata:\n");
2399 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002400 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002401 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002402 } else {
2403 write(fd, result.string(), result.size());
2404 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002405
2406 CameraParameters p = state.second->getShimParams();
2407 if (!p.isEmpty()) {
2408 result = String8::format(" Camera1 API shim is using parameters:\n ");
2409 write(fd, result.string(), result.size());
2410 p.dump(fd, args);
2411 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002412 }
2413
Ruben Brunkcc776712015-02-17 20:18:47 -08002414 auto clientDescriptor = mActiveClientManager.get(cameraId);
2415 if (clientDescriptor == nullptr) {
2416 result = String8::format(" Device %s is closed, no client instance\n",
2417 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002418 write(fd, result.string(), result.size());
2419 continue;
2420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002422 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2423 cameraId.string());
2424 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2425 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2426
2427 auto client = clientDescriptor->getValue();
2428 result.appendFormat("Client package: %s\n",
2429 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002430 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002431
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002432 client->dumpClient(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002434
2435 if (stateLocked) mCameraStatesLock.unlock();
2436
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002438 result = String8::format("\nNo active camera clients yet.\n");
2439 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 }
2441
2442 if (locked) mServiceLock.unlock();
2443
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002444 // Dump camera traces if there were any
2445 write(fd, "\n", 1);
2446 camera3::CameraTraces::dump(fd, args);
2447
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 // change logging level
2449 int n = args.size();
2450 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002451 String16 verboseOption("-v");
2452 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453 String8 levelStr(args[i+1]);
2454 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002455 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002457 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 }
2459 }
2460 }
2461 return NO_ERROR;
2462}
2463
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002464void CameraService::dumpEventLog(int fd) {
2465 String8 result = String8("\nPrior client events (most recent at top):\n");
2466
2467 Mutex::Autolock l(mLogLock);
2468 for (const auto& msg : mEventLog) {
2469 result.appendFormat(" %s\n", msg.string());
2470 }
2471
2472 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2473 result.append(" ...\n");
2474 } else if (mEventLog.size() == 0) {
2475 result.append(" [no events yet]\n");
2476 }
2477 result.append("\n");
2478
2479 write(fd, result.string(), result.size());
2480}
2481
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002482void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002483 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002484 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2485 if (mTorchClientMap[i] == who) {
2486 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002487 String8 cameraId = mTorchClientMap.keyAt(i);
2488 status_t res = mFlashlight->setTorchMode(cameraId, false);
2489 if (res) {
2490 ALOGE("%s: torch client died but couldn't turn off torch: "
2491 "%s (%d)", __FUNCTION__, strerror(-res), res);
2492 return;
2493 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002494 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002495 break;
2496 }
2497 }
2498}
2499
Ruben Brunkcc776712015-02-17 20:18:47 -08002500/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002501
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002502 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002503 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2504 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002505 */
2506
Ruben Brunka8ca9152015-04-07 14:23:40 -07002507 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2508
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002509 // check torch client
2510 handleTorchClientBinderDied(who);
2511
2512 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002513 if(!evictClientIdByRemote(who)) {
2514 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002515 return;
2516 }
2517
Ruben Brunkcc776712015-02-17 20:18:47 -08002518 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2519 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002520}
2521
Ruben Brunkcc776712015-02-17 20:18:47 -08002522void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2523 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002524}
2525
Ruben Brunkcc776712015-02-17 20:18:47 -08002526void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2527 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2528 // Do not lock mServiceLock here or can get into a deadlock from
2529 // connect() -> disconnect -> updateStatus
2530
2531 auto state = getCameraState(cameraId);
2532
2533 if (state == nullptr) {
2534 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2535 cameraId.string());
2536 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002537 }
2538
Ruben Brunkcc776712015-02-17 20:18:47 -08002539 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2540 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2541 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2542 (const String8& cameraId, ICameraServiceListener::Status status) {
2543
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002544 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2545 // Update torch status if it has a flash unit.
2546 Mutex::Autolock al(mTorchStatusMutex);
2547 ICameraServiceListener::TorchStatus torchStatus;
2548 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2549 NAME_NOT_FOUND) {
2550 ICameraServiceListener::TorchStatus newTorchStatus =
2551 status == ICameraServiceListener::STATUS_PRESENT ?
2552 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2553 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2554 if (torchStatus != newTorchStatus) {
2555 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2556 }
2557 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002558 }
2559
2560 Mutex::Autolock lock(mStatusListenerLock);
2561
2562 for (auto& listener : mListenerList) {
2563 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2564 int id = cameraIdToInt(cameraId);
2565 if (id != -1) listener->onStatusChanged(status, id);
2566 }
2567 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002568}
2569
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002570void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2571 const String8& cameraId) {
2572 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2573 if (proxyBinder == nullptr) return;
2574 String16 id(cameraId);
2575 proxyBinder->notifyCameraState(id, newState);
2576}
2577
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002578status_t CameraService::getTorchStatusLocked(
2579 const String8& cameraId,
2580 ICameraServiceListener::TorchStatus *status) const {
2581 if (!status) {
2582 return BAD_VALUE;
2583 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002584 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2585 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002586 // invalid camera ID or the camera doesn't have a flash unit
2587 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002588 }
2589
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002590 *status = mTorchStatusMap.valueAt(index);
2591 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002592}
2593
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002594status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002595 ICameraServiceListener::TorchStatus status) {
2596 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2597 if (index == NAME_NOT_FOUND) {
2598 return BAD_VALUE;
2599 }
2600 ICameraServiceListener::TorchStatus& item =
2601 mTorchStatusMap.editValueAt(index);
2602 item = status;
2603
2604 return OK;
2605}
2606
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607}; // namespace android