blob: 013250b461febe39f9710dbc7f5aed1df3b59819 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080031#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryBase.h>
35#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080036#include <binder/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070038#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080039#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <hardware/hardware.h>
41#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080042#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070044#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/Errors.h>
46#include <utils/Log.h>
47#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080048#include <utils/Trace.h>
49#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070050#include <system/camera_metadata.h>
51#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070054#include "api1/CameraClient.h"
55#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070057#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070058#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
60namespace android {
61
62// ----------------------------------------------------------------------------
63// Logging support -- this is for debugging only
64// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070065volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Steve Blockb8a80522011-12-20 16:23:08 +000067#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
70static void setLogLevel(int level) {
71 android_atomic_write(level, &gLogLevel);
72}
73
74// ----------------------------------------------------------------------------
75
Igor Murashkincba2c162013-03-20 15:56:31 -070076extern "C" {
77static void camera_device_status_change(
78 const struct camera_module_callbacks* callbacks,
79 int camera_id,
80 int new_status) {
81 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080082 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070083
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
Ruben Brunk6267b532015-04-30 17:44:07 -0700127CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH), mAllowedUsers(),
128 mSoundRef(0), mModule(0), mFlashlight(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000129 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800131
Igor Murashkincba2c162013-03-20 15:56:31 -0700132 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800133 this->torch_mode_status_change = android::torch_mode_status_change;
134
Ruben Brunkcc776712015-02-17 20:18:47 -0800135 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136}
137
Iliyan Malchev8951a972011-04-14 16:55:59 -0700138void CameraService::onFirstRef()
139{
Ruben Brunkcc776712015-02-17 20:18:47 -0800140 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800141
Iliyan Malchev8951a972011-04-14 16:55:59 -0700142 BnCameraService::onFirstRef();
143
Ruben Brunk99e69712015-05-26 17:25:07 -0700144 // Update battery life tracking if service is restarting
145 BatteryNotifier& notifier(BatteryNotifier::getInstance());
146 notifier.noteResetCamera();
147 notifier.noteResetFlashlight();
148
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800149 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700150 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
151 (const hw_module_t **)&rawModule);
152 if (err < 0) {
153 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
154 logServiceError("Could not load camera HAL module", err);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700155 mNumberOfCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700156 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700157 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800158
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700159 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 err = mModule->init();
161 if (err != OK) {
162 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
163 strerror(-err));
164 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800165
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700166 mNumberOfCameras = 0;
167 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
176 mFlashlight = new CameraFlashlight(*mModule, *this);
177 status_t res = mFlashlight->findFlashUnits();
178 if (res) {
179 // impossible because we haven't open any camera devices.
180 ALOGE("Failed to find flash units.");
181 }
182
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700183 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700184 for (int i = 0; i < mNumberOfCameras; i++) {
185 String8 cameraId = String8::format("%d", i);
186
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700187 // Get camera info
188
189 struct camera_info info;
190 bool haveInfo = true;
191 status_t rc = mModule->getCameraInfo(i, &info);
192 if (rc != NO_ERROR) {
193 ALOGE("%s: Received error loading camera info for device %d, cost and"
194 " conflicting devices fields set to defaults for this device.",
195 __FUNCTION__, i);
196 haveInfo = false;
197 }
198
199 // Check for backwards-compatibility support
200 if (haveInfo) {
201 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
202 delete mModule;
203 mModule = nullptr;
204 return;
205 }
206 }
207
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700208 // Defaults to use for cost and conflicting devices
209 int cost = 100;
210 char** conflicting_devices = nullptr;
211 size_t conflicting_devices_length = 0;
212
213 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700214 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
215 cost = info.resource_cost;
216 conflicting_devices = info.conflicting_devices;
217 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700218 }
219
220 std::set<String8> conflicting;
221 for (size_t i = 0; i < conflicting_devices_length; i++) {
222 conflicting.emplace(String8(conflicting_devices[i]));
223 }
224
225 // Initialize state for each camera device
226 {
227 Mutex::Autolock lock(mCameraStatesLock);
228 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
229 conflicting));
230 }
231
232 if (mFlashlight->hasFlashUnit(cameraId)) {
233 mTorchStatusMap.add(cameraId,
234 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
235 }
236 }
237
238 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
239 mModule->setCallbacks(this);
240 }
241
242 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
243
244 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
245 setUpVendorTags();
246 }
247
248 CameraDeviceFactory::registerService(this);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700249
250 CameraService::pingCameraServiceProxy();
251}
252
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700253sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Ruben Brunk2823ce02015-05-19 17:25:13 -0700254 sp<IServiceManager> sm = defaultServiceManager();
255 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
256 if (binder == nullptr) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700257 return nullptr;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700258 }
259 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700260 return proxyBinder;
261}
262
263void CameraService::pingCameraServiceProxy() {
264 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
265 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700266 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700267}
268
Mathias Agopian65ab4712010-07-14 17:59:35 -0700269CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800270 if (mModule) {
271 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800272 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800273 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800274 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800275 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276}
277
Ruben Brunkcc776712015-02-17 20:18:47 -0800278void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
279 camera_device_status_t newStatus) {
280 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700281 cameraId, newStatus);
282
Ruben Brunkcc776712015-02-17 20:18:47 -0800283 String8 id = String8::format("%d", cameraId);
284 std::shared_ptr<CameraState> state = getCameraState(id);
285
286 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700287 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
288 return;
289 }
290
Ruben Brunkcc776712015-02-17 20:18:47 -0800291 ICameraServiceListener::Status oldStatus = state->getStatus();
292
293 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
294 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700295 return;
296 }
297
Igor Murashkincba2c162013-03-20 15:56:31 -0700298 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700299 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
300 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800301 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700302 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800303 // Don't do this in updateStatus to avoid deadlock over mServiceLock
304 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700305
Ruben Brunkcc776712015-02-17 20:18:47 -0800306 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
307 // to this device until the status changes
308 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700309
Ruben Brunkcc776712015-02-17 20:18:47 -0800310 // Remove cached shim parameters
311 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700312
Ruben Brunkcc776712015-02-17 20:18:47 -0800313 // Remove the client from the list of active clients
314 clientToDisconnect = removeClientLocked(id);
315
316 // Notify the client of disconnection
Tom Keel056c93e2015-10-08 16:42:56 +0200317 if (clientToDisconnect != nullptr) {
318 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
319 CaptureResultExtras{});
320 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700321 }
322
Ruben Brunkcc776712015-02-17 20:18:47 -0800323 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
324 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700325
Ruben Brunkcc776712015-02-17 20:18:47 -0800326 // Disconnect client
327 if (clientToDisconnect.get() != nullptr) {
328 // Ensure not in binder RPC so client disconnect PID checks work correctly
329 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
330 "onDeviceStatusChanged must be called from the camera service process!");
331 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700332 }
333
Ruben Brunkcc776712015-02-17 20:18:47 -0800334 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700335 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
336 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
337 newStatus));
338 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800339 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700340 }
341
Igor Murashkincba2c162013-03-20 15:56:31 -0700342}
343
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800344void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800345 ICameraServiceListener::TorchStatus newStatus) {
346 Mutex::Autolock al(mTorchStatusMutex);
347 onTorchStatusChangedLocked(cameraId, newStatus);
348}
349
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800350void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800351 ICameraServiceListener::TorchStatus newStatus) {
352 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
353 __FUNCTION__, cameraId.string(), newStatus);
354
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800355 ICameraServiceListener::TorchStatus status;
356 status_t res = getTorchStatusLocked(cameraId, &status);
357 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700358 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
359 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800360 return;
361 }
362 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800363 return;
364 }
365
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800366 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800367 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700368 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800369 return;
370 }
371
Ruben Brunkcc776712015-02-17 20:18:47 -0800372 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700373 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700374 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700375 auto iter = mTorchUidMap.find(cameraId);
376 if (iter != mTorchUidMap.end()) {
377 int oldUid = iter->second.second;
378 int newUid = iter->second.first;
379 BatteryNotifier& notifier(BatteryNotifier::getInstance());
380 if (oldUid != newUid) {
381 // If the UID has changed, log the status and update current UID in mTorchUidMap
382 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
383 notifier.noteFlashlightOff(cameraId, oldUid);
384 }
385 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
386 notifier.noteFlashlightOn(cameraId, newUid);
387 }
388 iter->second.second = newUid;
389 } else {
390 // If the UID has not changed, log the status
391 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
392 notifier.noteFlashlightOn(cameraId, oldUid);
393 } else {
394 notifier.noteFlashlightOff(cameraId, oldUid);
395 }
396 }
397 }
398 }
399
400 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800401 Mutex::Autolock lock(mStatusListenerLock);
402 for (auto& i : mListenerList) {
403 i->onTorchStatusChanged(newStatus, String16{cameraId});
404 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800405 }
406}
407
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700409 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700410 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
411}
412
413int32_t CameraService::getNumberOfCameras(int type) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700414 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700415 switch (type) {
416 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
417 return mNumberOfNormalCameras;
418 case CAMERA_TYPE_ALL:
419 return mNumberOfCameras;
420 default:
421 ALOGW("%s: Unknown camera type %d, returning 0",
422 __FUNCTION__, type);
423 return 0;
424 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425}
426
427status_t CameraService::getCameraInfo(int cameraId,
428 struct CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700429 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700430 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700431 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700432 }
433
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
435 return BAD_VALUE;
436 }
437
Iliyan Malchev8951a972011-04-14 16:55:59 -0700438 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700439 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800440 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700441 cameraInfo->facing = info.facing;
442 cameraInfo->orientation = info.orientation;
443 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444}
445
Ruben Brunkcc776712015-02-17 20:18:47 -0800446int CameraService::cameraIdToInt(const String8& cameraId) {
447 errno = 0;
448 size_t pos = 0;
449 int ret = stoi(std::string{cameraId.string()}, &pos);
450 if (errno != 0 || pos != cameraId.size()) {
451 return -1;
452 }
453 return ret;
454}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700455
456status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700457 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700458 status_t ret = OK;
459 struct CameraInfo info;
460 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
461 return ret;
462 }
463
464 CameraMetadata shimInfo;
465 int32_t orientation = static_cast<int32_t>(info.orientation);
466 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
467 return ret;
468 }
469
470 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
471 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
472 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
473 return ret;
474 }
475
Igor Murashkin65d14b92014-06-17 12:03:20 -0700476 CameraParameters shimParams;
477 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
478 // Error logged by callee
479 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700480 }
481
482 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700483 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700484 Vector<int32_t> formats;
485 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700486 {
487 shimParams.getSupportedPreviewSizes(/*out*/sizes);
488 shimParams.getSupportedPreviewFormats(/*out*/formats);
489 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700490 }
491
492 // Always include IMPLEMENTATION_DEFINED
493 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
494
495 const size_t INTS_PER_CONFIG = 4;
496
497 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700498 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
499
500 Vector<int32_t> streamConfigs;
501 streamConfigs.setCapacity(streamConfigSize);
502
Ruben Brunkb2119af2014-05-09 19:57:56 -0700503 for (size_t i = 0; i < formats.size(); ++i) {
504 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700505 streamConfigs.add(formats[i]);
506 streamConfigs.add(sizes[j].width);
507 streamConfigs.add(sizes[j].height);
508 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700509 }
510 }
511
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700512 for (size_t i = 0; i < jpegSizes.size(); ++i) {
513 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
514 streamConfigs.add(jpegSizes[i].width);
515 streamConfigs.add(jpegSizes[i].height);
516 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
517 }
518
Ruben Brunkb2119af2014-05-09 19:57:56 -0700519 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700520 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700521 return ret;
522 }
523
524 int64_t fakeMinFrames[0];
525 // TODO: Fixme, don't fake min frame durations.
526 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
527 fakeMinFrames, 0)) != OK) {
528 return ret;
529 }
530
531 int64_t fakeStalls[0];
532 // TODO: Fixme, don't fake stall durations.
533 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
534 fakeStalls, 0)) != OK) {
535 return ret;
536 }
537
538 *cameraInfo = shimInfo;
539 return OK;
540}
541
Zhijun He2b59be82013-09-25 10:14:30 -0700542status_t CameraService::getCameraCharacteristics(int cameraId,
543 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700544 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700545 if (!cameraInfo) {
546 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
547 return BAD_VALUE;
548 }
549
550 if (!mModule) {
551 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
552 return -ENODEV;
553 }
554
Zhijun He2b59be82013-09-25 10:14:30 -0700555 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
556 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
557 return BAD_VALUE;
558 }
559
560 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700561 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800562 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700563 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
564 /**
565 * Backwards compatibility mode for old HALs:
566 * - Convert CameraInfo into static CameraMetadata properties.
567 * - Retrieve cached CameraParameters for this camera. If none exist,
568 * attempt to open CameraClient and retrieve the CameraParameters.
569 * - Convert cached CameraParameters into static CameraMetadata
570 * properties.
571 */
572 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700573
Ruben Brunkb2119af2014-05-09 19:57:56 -0700574 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
575 return ret;
576 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700577
Ruben Brunkb2119af2014-05-09 19:57:56 -0700578 } else {
579 /**
580 * Normal HAL 2.1+ codepath.
581 */
582 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800583 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700584 *cameraInfo = info.static_camera_characteristics;
585 }
Zhijun He2b59be82013-09-25 10:14:30 -0700586
587 return ret;
588}
589
Ruben Brunkcc776712015-02-17 20:18:47 -0800590int CameraService::getCallingPid() {
591 return IPCThreadState::self()->getCallingPid();
592}
593
594int CameraService::getCallingUid() {
595 return IPCThreadState::self()->getCallingUid();
596}
597
598String8 CameraService::getFormattedCurrentTime() {
599 time_t now = time(nullptr);
600 char formattedTime[64];
601 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
602 return String8(formattedTime);
603}
604
605int CameraService::getCameraPriorityFromProcState(int procState) {
606 // Find the priority for the camera usage based on the process state. Higher priority clients
607 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700608 if (procState < 0) {
609 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
610 procState);
611 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800612 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700613 // Treat sleeping TOP processes the same as regular TOP processes, for
614 // access priority. This is important for lock-screen camera launch scenarios
615 if (procState == PROCESS_STATE_TOP_SLEEPING) {
616 procState = PROCESS_STATE_TOP;
617 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700618 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800619}
620
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800621status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700622 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800623 if (!mModule) {
624 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
625 return -ENODEV;
626 }
627
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800628 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
629 return OK;
630}
631
Igor Murashkin634a5152013-02-20 17:15:11 -0800632int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700633 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800634 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800635 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800636 return -1;
637 }
638
639 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800640 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800641 deviceVersion = info.device_version;
642 } else {
643 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
644 }
645
646 if (facing) {
647 *facing = info.facing;
648 }
649
650 return deviceVersion;
651}
652
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700653status_t CameraService::filterGetInfoErrorCode(status_t err) {
654 switch(err) {
655 case NO_ERROR:
656 case -EINVAL:
657 return err;
658 default:
659 break;
660 }
661 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800662}
663
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800664bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700665 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800666 vendor_tag_ops_t vOps = vendor_tag_ops_t();
667
668 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800669 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800670 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
671 return false;
672 }
673
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800674 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800675
676 // Ensure all vendor operations are present
677 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
678 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
679 vOps.get_tag_type == NULL) {
680 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
681 , __FUNCTION__);
682 return false;
683 }
684
685 // Read all vendor tag definitions into a descriptor
686 sp<VendorTagDescriptor> desc;
687 status_t res;
688 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
689 != OK) {
690 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
691 "received error %s (%d). Camera clients will not be able to use"
692 "vendor tags", __FUNCTION__, strerror(res), res);
693 return false;
694 }
695
696 // Set the global descriptor to use with camera metadata
697 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
698 return true;
699}
700
Ruben Brunkcc776712015-02-17 20:18:47 -0800701status_t CameraService::makeClient(const sp<CameraService>& cameraService,
702 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
703 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
704 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
705 /*out*/sp<BasicClient>* client) {
706
707 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
708 int id = cameraIdToInt(cameraId);
709 if (id == -1) {
710 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
711 cameraId.string());
712 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700713 }
714
Ruben Brunkcc776712015-02-17 20:18:47 -0800715 if (halVersion < 0 || halVersion == deviceVersion) {
716 // Default path: HAL version is unspecified by caller, create CameraClient
717 // based on device version reported by the HAL.
718 switch(deviceVersion) {
719 case CAMERA_DEVICE_API_VERSION_1_0:
720 if (effectiveApiLevel == API_1) { // Camera1 API route
721 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
722 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
723 clientPid, clientUid, getpid(), legacyMode);
724 } else { // Camera2 API route
725 ALOGW("Camera using old HAL version: %d", deviceVersion);
726 return -EOPNOTSUPP;
727 }
728 break;
729 case CAMERA_DEVICE_API_VERSION_2_0:
730 case CAMERA_DEVICE_API_VERSION_2_1:
731 case CAMERA_DEVICE_API_VERSION_3_0:
732 case CAMERA_DEVICE_API_VERSION_3_1:
733 case CAMERA_DEVICE_API_VERSION_3_2:
734 case CAMERA_DEVICE_API_VERSION_3_3:
735 if (effectiveApiLevel == API_1) { // Camera1 API route
736 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
737 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
738 clientPid, clientUid, servicePid, legacyMode);
739 } else { // Camera2 API route
740 sp<ICameraDeviceCallbacks> tmp =
741 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
742 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
743 facing, clientPid, clientUid, servicePid);
744 }
745 break;
746 default:
747 // Should not be reachable
748 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
749 return INVALID_OPERATION;
750 }
751 } else {
752 // A particular HAL version is requested by caller. Create CameraClient
753 // based on the requested HAL version.
754 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
755 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
756 // Only support higher HAL version device opened as HAL1.0 device.
757 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
758 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
759 clientPid, clientUid, servicePid, legacyMode);
760 } else {
761 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
762 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
763 " opened as HAL %x device", halVersion, deviceVersion,
764 CAMERA_DEVICE_API_VERSION_1_0);
765 return INVALID_OPERATION;
766 }
767 }
768 return NO_ERROR;
769}
770
Ruben Brunk6267b532015-04-30 17:44:07 -0700771String8 CameraService::toString(std::set<userid_t> intSet) {
772 String8 s("");
773 bool first = true;
774 for (userid_t i : intSet) {
775 if (first) {
776 s.appendFormat("%d", i);
777 first = false;
778 } else {
779 s.appendFormat(", %d", i);
780 }
781 }
782 return s;
783}
784
Ruben Brunkcc776712015-02-17 20:18:47 -0800785status_t CameraService::initializeShimMetadata(int cameraId) {
786 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700787
788 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800789 String8 id = String8::format("%d", cameraId);
790 status_t ret = NO_ERROR;
791 sp<Client> tmp = nullptr;
792 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
793 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
794 false, true, tmp)) != NO_ERROR) {
795 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
796 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700797 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800798 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700799}
800
Igor Murashkin65d14b92014-06-17 12:03:20 -0700801status_t CameraService::getLegacyParametersLazy(int cameraId,
802 /*out*/
803 CameraParameters* parameters) {
804
805 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
806
807 status_t ret = 0;
808
809 if (parameters == NULL) {
810 ALOGE("%s: parameters must not be null", __FUNCTION__);
811 return BAD_VALUE;
812 }
813
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 String8 id = String8::format("%d", cameraId);
815
816 // Check if we already have parameters
817 {
818 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700819 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 auto cameraState = getCameraState(id);
821 if (cameraState == nullptr) {
822 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
823 return BAD_VALUE;
824 }
825 CameraParameters p = cameraState->getShimParams();
826 if (!p.isEmpty()) {
827 *parameters = p;
828 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700829 }
830 }
831
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 int64_t token = IPCThreadState::self()->clearCallingIdentity();
833 ret = initializeShimMetadata(cameraId);
834 IPCThreadState::self()->restoreCallingIdentity(token);
835 if (ret != NO_ERROR) {
836 // Error already logged by callee
837 return ret;
838 }
839
840 // Check for parameters again
841 {
842 // Scope for service lock
843 Mutex::Autolock lock(mServiceLock);
844 auto cameraState = getCameraState(id);
845 if (cameraState == nullptr) {
846 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
847 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700848 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800849 CameraParameters p = cameraState->getShimParams();
850 if (!p.isEmpty()) {
851 *parameters = p;
852 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700853 }
854 }
855
Ruben Brunkcc776712015-02-17 20:18:47 -0800856 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
857 __FUNCTION__);
858 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700859}
860
Ruben Brunk36597b22015-03-20 22:15:57 -0700861status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
862 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800863
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500865
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800866 if (clientUid == USE_CALLING_UID) {
867 clientUid = getCallingUid();
868 } else {
869 // We only trust our own process to forward client UIDs
870 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700871 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
872 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700873 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800874 }
875 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876
Iliyan Malchev8951a972011-04-14 16:55:59 -0700877 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800878 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
879 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700880 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700881 }
882
Ruben Brunkcc776712015-02-17 20:18:47 -0800883 if (getCameraState(cameraId) == nullptr) {
884 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
885 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700886 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887 }
888
Ruben Brunkcc776712015-02-17 20:18:47 -0800889 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800890 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800891 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700892 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800893 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
894 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800895 if (strcmp(value, "1") == 0) {
896 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800897 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
898 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700899 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800900 }
901
Ruben Brunka8ca9152015-04-07 14:23:40 -0700902 // Only allow clients who are being used by the current foreground device user, unless calling
903 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700904 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
905 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
906 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
907 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700908 return PERMISSION_DENIED;
909 }
910
Ruben Brunkcc776712015-02-17 20:18:47 -0800911 return checkIfDeviceIsUsable(cameraId);
912}
913
914status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
915 auto cameraState = getCameraState(cameraId);
916 int callingPid = getCallingPid();
917 if (cameraState == nullptr) {
918 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
919 cameraId.string());
920 return -ENODEV;
921 }
922
923 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700924 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800925 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
926 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700927 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700928 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800929 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
930 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700931 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700932 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700933
Ruben Brunkcc776712015-02-17 20:18:47 -0800934 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800935}
936
Ruben Brunkcc776712015-02-17 20:18:47 -0800937void CameraService::finishConnectLocked(const sp<BasicClient>& client,
938 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800939
Ruben Brunkcc776712015-02-17 20:18:47 -0800940 // Make a descriptor for the incoming client
941 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
942 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
943
944 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
945 String8(client->getPackageName()));
946
947 if (evicted.size() > 0) {
948 // This should never happen - clients should already have been removed in disconnect
949 for (auto& i : evicted) {
950 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
951 __FUNCTION__, i->getKey().string());
952 }
953
954 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
955 __FUNCTION__);
956 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700957
958 // And register a death notification for the client callback. Do
959 // this last to avoid Binder policy where a nested Binder
960 // transaction might be pre-empted to service the client death
961 // notification if the client process dies before linkToDeath is
962 // invoked.
963 sp<IBinder> remoteCallback = client->getRemote();
964 if (remoteCallback != nullptr) {
965 remoteCallback->linkToDeath(this);
966 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800967}
968
969status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
970 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
971 /*out*/
972 sp<BasicClient>* client,
973 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700974 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800975 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700976 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800977 DescriptorPtr clientDescriptor;
978 {
979 if (effectiveApiLevel == API_1) {
980 // If we are using API1, any existing client for this camera ID with the same remote
981 // should be returned rather than evicted to allow MediaRecorder to work properly.
982
983 auto current = mActiveClientManager.get(cameraId);
984 if (current != nullptr) {
985 auto clientSp = current->getValue();
986 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700987 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
988 ALOGW("CameraService connect called from same client, but with a different"
989 " API level, evicting prior client...");
990 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700992 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800993 *client = clientSp;
994 return NO_ERROR;
995 }
996 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800997 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800998 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800999
Ruben Brunkcc776712015-02-17 20:18:47 -08001000 // Return error if the device was unplugged or removed by the HAL for some reason
1001 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1002 return ret;
1003 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001004
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 // Get current active client PIDs
1006 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1007 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001008
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001009 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1010 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1011 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1012 // not have an out-of-class definition.
1013 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001014
Ruben Brunkcc776712015-02-17 20:18:47 -08001015 // Get priorites of all active PIDs
1016 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1017 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001018
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 // Update all active clients' priorities
1020 std::map<int,int> pidToPriorityMap;
1021 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1022 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1023 }
1024 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001025
Ruben Brunkcc776712015-02-17 20:18:47 -08001026 // Get state for the given cameraId
1027 auto state = getCameraState(cameraId);
1028 if (state == nullptr) {
1029 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1030 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001031 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001032 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001033
1034 // Make descriptor for incoming client
1035 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1036 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1037 state->getConflicting(),
1038 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1039
1040 // Find clients that would be evicted
1041 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1042
1043 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1044 // background, so we cannot do evictions
1045 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1046 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1047 " priority).", clientPid);
1048
1049 sp<BasicClient> clientSp = clientDescriptor->getValue();
1050 String8 curTime = getFormattedCurrentTime();
1051 auto incompatibleClients =
1052 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1053
1054 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001055 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001056 cameraId.string(), packageName.string(), clientPid,
1057 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1058
1059 for (auto& i : incompatibleClients) {
1060 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1061 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1062 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1063 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001064 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1065 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1066 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1067 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001068 }
1069
1070 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001071 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001072 mEventLog.add(msg);
1073
1074 return -EBUSY;
1075 }
1076
1077 for (auto& i : evicted) {
1078 sp<BasicClient> clientSp = i->getValue();
1079 if (clientSp.get() == nullptr) {
1080 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1081
1082 // TODO: Remove this
1083 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1084 __FUNCTION__);
1085 mActiveClientManager.remove(i);
1086 continue;
1087 }
1088
1089 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1090 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001091 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001092
Ruben Brunkcc776712015-02-17 20:18:47 -08001093 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001094 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1095 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1096 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001097 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1098 i->getOwnerId(), i->getPriority(), cameraId.string(),
1099 packageName.string(), clientPid,
1100 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1101
1102 // Notify the client of disconnection
1103 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1104 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001105 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001106 }
1107
Ruben Brunkcc776712015-02-17 20:18:47 -08001108 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1109 // other clients from connecting in mServiceLockWrapper if held
1110 mServiceLock.unlock();
1111
1112 // Clear caller identity temporarily so client disconnect PID checks work correctly
1113 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1114
1115 // Destroy evicted clients
1116 for (auto& i : evictedClients) {
1117 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001118 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001119 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001120
1121 IPCThreadState::self()->restoreCallingIdentity(token);
1122
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001123 for (const auto& i : evictedClients) {
1124 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1125 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1126 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1127 if (ret == TIMED_OUT) {
1128 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1129 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1130 mActiveClientManager.toString().string());
1131 return -EBUSY;
1132 }
1133 if (ret != NO_ERROR) {
1134 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1135 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1136 ret, mActiveClientManager.toString().string());
1137 return ret;
1138 }
1139 }
1140
1141 evictedClients.clear();
1142
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 // Once clients have been disconnected, relock
1144 mServiceLock.lock();
1145
1146 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1147 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1148 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001149 }
1150
Ruben Brunkcc776712015-02-17 20:18:47 -08001151 *partial = clientDescriptor;
1152 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001153}
1154
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001155status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001156 const sp<ICameraClient>& cameraClient,
1157 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001158 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001159 int clientUid,
1160 /*out*/
1161 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001162
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001163 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001164 status_t ret = NO_ERROR;
1165 String8 id = String8::format("%d", cameraId);
1166 sp<Client> client = nullptr;
1167 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001168 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001169
Ruben Brunkcc776712015-02-17 20:18:47 -08001170 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001171 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001172 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001173 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 }
1175
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001176 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001177 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178}
1179
Zhijun Heb10cdad2014-06-16 16:38:35 -07001180status_t CameraService::connectLegacy(
1181 const sp<ICameraClient>& cameraClient,
1182 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001183 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001184 int clientUid,
1185 /*out*/
1186 sp<ICamera>& device) {
1187
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001188 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001189 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001190 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001191 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001192 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001193 /*
1194 * Either the HAL version is unspecified in which case this just creates
1195 * a camera client selected by the latest device version, or
1196 * it's a particular version in which case the HAL must supported
1197 * the open_legacy call
1198 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001199 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001200 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001201 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001202 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001203 return INVALID_OPERATION;
1204 }
1205
Ruben Brunkcc776712015-02-17 20:18:47 -08001206 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001207 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001208 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001209 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001210
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001212 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001213 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001214 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001215 }
1216
Zhijun Heb10cdad2014-06-16 16:38:35 -07001217 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001218 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001219}
1220
Ruben Brunkcc776712015-02-17 20:18:47 -08001221status_t CameraService::connectDevice(
1222 const sp<ICameraDeviceCallbacks>& cameraCb,
1223 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001224 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 int clientUid,
1226 /*out*/
1227 sp<ICameraDeviceUser>& device) {
1228
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001229 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001230 status_t ret = NO_ERROR;
1231 String8 id = String8::format("%d", cameraId);
1232 sp<CameraDeviceClient> client = nullptr;
1233 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001234 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001235 /*out*/client);
1236
1237 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001238 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001239 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001240 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001241 }
1242
Ruben Brunkcc776712015-02-17 20:18:47 -08001243 device = client;
1244 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001245}
1246
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001247status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1248 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001249
1250 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001251 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001252 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001253 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001254 }
1255
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001256 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001257 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001258
1259 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001260 auto state = getCameraState(id);
1261 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001262 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001263 return -EINVAL;
1264 }
1265
1266 ICameraServiceListener::Status cameraStatus = state->getStatus();
1267 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1268 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001269 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001270 return -EINVAL;
1271 }
1272
1273 {
1274 Mutex::Autolock al(mTorchStatusMutex);
1275 ICameraServiceListener::TorchStatus status;
1276 status_t res = getTorchStatusLocked(id, &status);
1277 if (res) {
1278 ALOGE("%s: getting current torch status failed for camera %s",
1279 __FUNCTION__, id.string());
1280 return -EINVAL;
1281 }
1282
1283 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001284 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001285 ALOGE("%s: torch mode of camera %s is not available because "
1286 "camera is in use", __FUNCTION__, id.string());
1287 return -EBUSY;
1288 } else {
1289 ALOGE("%s: torch mode of camera %s is not available due to "
1290 "insufficient resources", __FUNCTION__, id.string());
1291 return -EUSERS;
1292 }
1293 }
1294 }
1295
Ruben Brunk99e69712015-05-26 17:25:07 -07001296 {
1297 // Update UID map - this is used in the torch status changed callbacks, so must be done
1298 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001299 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001300 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1301 mTorchUidMap[id].first = uid;
1302 mTorchUidMap[id].second = uid;
1303 } else {
1304 // Set the pending UID
1305 mTorchUidMap[id].first = uid;
1306 }
1307 }
1308
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001309 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001310
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001311 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001312 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1313 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001314 return res;
1315 }
1316
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001317 {
1318 // update the link to client's death
1319 Mutex::Autolock al(mTorchClientMapMutex);
1320 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001321 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001322 if (enabled) {
1323 if (index == NAME_NOT_FOUND) {
1324 mTorchClientMap.add(id, clientBinder);
1325 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001326 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001327 mTorchClientMap.replaceValueAt(index, clientBinder);
1328 }
1329 clientBinder->linkToDeath(this);
1330 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001331 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001332 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001333 }
1334
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001335 return OK;
1336}
1337
Ruben Brunk6267b532015-04-30 17:44:07 -07001338void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001339 ATRACE_CALL();
1340
Ruben Brunk36597b22015-03-20 22:15:57 -07001341 switch(eventId) {
1342 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001343 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001344 break;
1345 }
1346 case ICameraService::NO_EVENT:
1347 default: {
1348 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1349 eventId);
1350 break;
1351 }
1352 }
1353}
1354
Ruben Brunk99e69712015-05-26 17:25:07 -07001355status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001356 ATRACE_CALL();
1357
Igor Murashkinbfc99152013-02-27 12:55:20 -08001358 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001359
Ruben Brunk3450ba72015-06-16 11:00:37 -07001360 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001361 ALOGE("%s: Listener must not be null", __FUNCTION__);
1362 return BAD_VALUE;
1363 }
1364
Igor Murashkinbfc99152013-02-27 12:55:20 -08001365 Mutex::Autolock lock(mServiceLock);
1366
Ruben Brunkcc776712015-02-17 20:18:47 -08001367 {
1368 Mutex::Autolock lock(mStatusListenerLock);
1369 for (auto& it : mListenerList) {
1370 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1371 ALOGW("%s: Tried to add listener %p which was already subscribed",
1372 __FUNCTION__, listener.get());
1373 return ALREADY_EXISTS;
1374 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001375 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001376
1377 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001378 }
1379
Igor Murashkinbfc99152013-02-27 12:55:20 -08001380
Igor Murashkincba2c162013-03-20 15:56:31 -07001381 /* Immediately signal current status to this listener only */
1382 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001383 Mutex::Autolock lock(mCameraStatesLock);
1384 for (auto& i : mCameraStates) {
1385 // TODO: Update binder to use String16 for camera IDs and remove;
1386 int id = cameraIdToInt(i.first);
1387 if (id == -1) continue;
1388
1389 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001390 }
1391 }
1392
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001393 /* Immediately signal current torch status to this listener only */
1394 {
1395 Mutex::Autolock al(mTorchStatusMutex);
1396 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001397 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1398 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001399 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001400 }
1401
Igor Murashkinbfc99152013-02-27 12:55:20 -08001402 return OK;
1403}
Ruben Brunkcc776712015-02-17 20:18:47 -08001404
1405status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001406 ATRACE_CALL();
1407
Igor Murashkinbfc99152013-02-27 12:55:20 -08001408 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1409
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001410 if (listener == 0) {
1411 ALOGE("%s: Listener must not be null", __FUNCTION__);
1412 return BAD_VALUE;
1413 }
1414
Igor Murashkinbfc99152013-02-27 12:55:20 -08001415 Mutex::Autolock lock(mServiceLock);
1416
Ruben Brunkcc776712015-02-17 20:18:47 -08001417 {
1418 Mutex::Autolock lock(mStatusListenerLock);
1419 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1420 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1421 mListenerList.erase(it);
1422 return OK;
1423 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001424 }
1425 }
1426
1427 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1428 __FUNCTION__, listener.get());
1429
1430 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001431}
1432
Ruben Brunkcc776712015-02-17 20:18:47 -08001433status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001434
1435 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001436 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1437
1438 if (parameters == NULL) {
1439 ALOGE("%s: parameters must not be null", __FUNCTION__);
1440 return BAD_VALUE;
1441 }
1442
1443 status_t ret = 0;
1444
1445 CameraParameters shimParams;
1446 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1447 // Error logged by caller
1448 return ret;
1449 }
1450
1451 String8 shimParamsString8 = shimParams.flatten();
1452 String16 shimParamsString16 = String16(shimParamsString8);
1453
1454 *parameters = shimParamsString16;
1455
1456 return OK;
1457}
1458
1459status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001460 ATRACE_CALL();
1461
Igor Murashkin65d14b92014-06-17 12:03:20 -07001462 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1463
1464 switch (apiVersion) {
1465 case API_VERSION_1:
1466 case API_VERSION_2:
1467 break;
1468 default:
1469 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1470 return BAD_VALUE;
1471 }
1472
1473 int facing = -1;
1474 int deviceVersion = getDeviceVersion(cameraId, &facing);
1475
1476 switch(deviceVersion) {
1477 case CAMERA_DEVICE_API_VERSION_1_0:
1478 case CAMERA_DEVICE_API_VERSION_2_0:
1479 case CAMERA_DEVICE_API_VERSION_2_1:
1480 case CAMERA_DEVICE_API_VERSION_3_0:
1481 case CAMERA_DEVICE_API_VERSION_3_1:
1482 if (apiVersion == API_VERSION_2) {
1483 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1484 __FUNCTION__, cameraId);
1485 return -EOPNOTSUPP;
1486 } else { // if (apiVersion == API_VERSION_1) {
1487 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1488 __FUNCTION__, cameraId);
1489 return OK;
1490 }
1491 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001492 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001493 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1494 __FUNCTION__, cameraId);
1495 return OK;
1496 case -1:
1497 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1498 return BAD_VALUE;
1499 default:
1500 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1501 return INVALID_OPERATION;
1502 }
1503
1504 return OK;
1505}
1506
Ruben Brunkcc776712015-02-17 20:18:47 -08001507void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001508 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001509 for (auto& i : mActiveClientManager.getAll()) {
1510 auto clientSp = i->getValue();
1511 if (clientSp.get() == client) {
1512 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001513 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001514 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001515}
1516
Ruben Brunkcc776712015-02-17 20:18:47 -08001517bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1518 const int callingPid = getCallingPid();
1519 const int servicePid = getpid();
1520 bool ret = false;
1521 {
1522 // Acquire mServiceLock and prevent other clients from connecting
1523 std::unique_ptr<AutoConditionLock> lock =
1524 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001525
Igor Murashkin634a5152013-02-20 17:15:11 -08001526
Ruben Brunkcc776712015-02-17 20:18:47 -08001527 std::vector<sp<BasicClient>> evicted;
1528 for (auto& i : mActiveClientManager.getAll()) {
1529 auto clientSp = i->getValue();
1530 if (clientSp.get() == nullptr) {
1531 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1532 mActiveClientManager.remove(i);
1533 continue;
1534 }
1535 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1536 callingPid == clientSp->getClientPid())) {
1537 mActiveClientManager.remove(i);
1538 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001539
Ruben Brunkcc776712015-02-17 20:18:47 -08001540 // Notify the client of disconnection
1541 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1542 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001543 }
1544 }
1545
Ruben Brunkcc776712015-02-17 20:18:47 -08001546 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1547 // other clients from connecting in mServiceLockWrapper if held
1548 mServiceLock.unlock();
1549
Ruben Brunk36597b22015-03-20 22:15:57 -07001550 // Do not clear caller identity, remote caller should be client proccess
1551
Ruben Brunkcc776712015-02-17 20:18:47 -08001552 for (auto& i : evicted) {
1553 if (i.get() != nullptr) {
1554 i->disconnect();
1555 ret = true;
1556 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001557 }
1558
Ruben Brunkcc776712015-02-17 20:18:47 -08001559 // Reacquire mServiceLock
1560 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001561
Ruben Brunkcc776712015-02-17 20:18:47 -08001562 } // lock is destroyed, allow further connect calls
1563
1564 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001565}
1566
Igor Murashkinecf17e82012-10-02 16:05:11 -07001567
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001568/**
1569 * Check camera capabilities, such as support for basic color operation
1570 */
1571int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1572
1573 // Assume all devices pre-v3.3 are backward-compatible
1574 bool isBackwardCompatible = true;
1575 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1576 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1577 isBackwardCompatible = false;
1578 status_t res;
1579 camera_metadata_ro_entry_t caps;
1580 res = find_camera_metadata_ro_entry(
1581 info.static_camera_characteristics,
1582 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1583 &caps);
1584 if (res != 0) {
1585 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1586 __FUNCTION__, id);
1587 caps.count = 0;
1588 }
1589 for (size_t i = 0; i < caps.count; i++) {
1590 if (caps.data.u8[i] ==
1591 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1592 isBackwardCompatible = true;
1593 break;
1594 }
1595 }
1596 }
1597
1598 if (!isBackwardCompatible) {
1599 mNumberOfNormalCameras--;
1600 *latestStrangeCameraId = id;
1601 } else {
1602 if (id > *latestStrangeCameraId) {
1603 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1604 "This is not allowed due backward-compatibility requirements",
1605 __FUNCTION__, id, *latestStrangeCameraId);
1606 logServiceError("Invalid order of camera devices", ENODEV);
1607 mNumberOfCameras = 0;
1608 mNumberOfNormalCameras = 0;
1609 return INVALID_OPERATION;
1610 }
1611 }
1612 return OK;
1613}
1614
Ruben Brunkcc776712015-02-17 20:18:47 -08001615std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1616 const String8& cameraId) const {
1617 std::shared_ptr<CameraState> state;
1618 {
1619 Mutex::Autolock lock(mCameraStatesLock);
1620 auto iter = mCameraStates.find(cameraId);
1621 if (iter != mCameraStates.end()) {
1622 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 }
1624 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001625 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626}
1627
Ruben Brunkcc776712015-02-17 20:18:47 -08001628sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1629 // Remove from active clients list
1630 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1631 if (clientDescriptorPtr == nullptr) {
1632 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1633 cameraId.string());
1634 return sp<BasicClient>{nullptr};
1635 }
1636
1637 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001638}
1639
Ruben Brunk6267b532015-04-30 17:44:07 -07001640void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001641 // Acquire mServiceLock and prevent other clients from connecting
1642 std::unique_ptr<AutoConditionLock> lock =
1643 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1644
Ruben Brunk6267b532015-04-30 17:44:07 -07001645 std::set<userid_t> newAllowedUsers;
1646 for (size_t i = 0; i < length; i++) {
1647 if (newUserId[i] < 0) {
1648 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1649 __FUNCTION__, newUserId[i]);
1650 return;
1651 }
1652 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001653 }
1654
Ruben Brunka8ca9152015-04-07 14:23:40 -07001655
Ruben Brunk6267b532015-04-30 17:44:07 -07001656 if (newAllowedUsers == mAllowedUsers) {
1657 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1658 return;
1659 }
1660
1661 logUserSwitch(mAllowedUsers, newAllowedUsers);
1662
1663 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001664
1665 // Current user has switched, evict all current clients.
1666 std::vector<sp<BasicClient>> evicted;
1667 for (auto& i : mActiveClientManager.getAll()) {
1668 auto clientSp = i->getValue();
1669
1670 if (clientSp.get() == nullptr) {
1671 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1672 continue;
1673 }
1674
Ruben Brunk6267b532015-04-30 17:44:07 -07001675 // Don't evict clients that are still allowed.
1676 uid_t clientUid = clientSp->getClientUid();
1677 userid_t clientUserId = multiuser_get_user_id(clientUid);
1678 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1679 continue;
1680 }
1681
Ruben Brunk36597b22015-03-20 22:15:57 -07001682 evicted.push_back(clientSp);
1683
1684 String8 curTime = getFormattedCurrentTime();
1685
1686 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1687 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001688
Ruben Brunk36597b22015-03-20 22:15:57 -07001689 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001690 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001691 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001692 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1693 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001694
1695 }
1696
1697 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1698 // blocking other clients from connecting in mServiceLockWrapper if held.
1699 mServiceLock.unlock();
1700
1701 // Clear caller identity temporarily so client disconnect PID checks work correctly
1702 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1703
1704 for (auto& i : evicted) {
1705 i->disconnect();
1706 }
1707
1708 IPCThreadState::self()->restoreCallingIdentity(token);
1709
1710 // Reacquire mServiceLock
1711 mServiceLock.lock();
1712}
Ruben Brunkcc776712015-02-17 20:18:47 -08001713
Ruben Brunka8ca9152015-04-07 14:23:40 -07001714void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001715 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001716 Mutex::Autolock l(mLogLock);
1717 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718}
1719
Ruben Brunka8ca9152015-04-07 14:23:40 -07001720void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001721 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001722 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001723 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001724 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001725}
1726
1727void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001728 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001729 // Log the clients evicted
1730 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001731 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001732}
1733
1734void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001735 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001736 // Log the client rejected
1737 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001738 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001739}
1740
Ruben Brunk6267b532015-04-30 17:44:07 -07001741void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1742 const std::set<userid_t>& newUserIds) {
1743 String8 newUsers = toString(newUserIds);
1744 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001745 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001746 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1747 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001748}
1749
1750void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1751 // Log the device removal
1752 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1753}
1754
1755void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1756 // Log the device removal
1757 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1758}
1759
1760void CameraService::logClientDied(int clientPid, const char* reason) {
1761 // Log the device removal
1762 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001763}
1764
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001765void CameraService::logServiceError(const char* msg, int errorCode) {
1766 String8 curTime = getFormattedCurrentTime();
1767 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1768}
1769
Ruben Brunk36597b22015-03-20 22:15:57 -07001770status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1771 uint32_t flags) {
1772
1773 const int pid = getCallingPid();
1774 const int selfPid = getpid();
1775
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 // Permission checks
1777 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001778 case BnCameraService::CONNECT:
1779 case BnCameraService::CONNECT_DEVICE:
1780 case BnCameraService::CONNECT_LEGACY: {
1781 if (pid != selfPid) {
1782 // we're called from a different process, do the real check
1783 if (!checkCallingPermission(
1784 String16("android.permission.CAMERA"))) {
1785 const int uid = getCallingUid();
1786 ALOGE("Permission Denial: "
1787 "can't use the camera pid=%d, uid=%d", pid, uid);
1788 return PERMISSION_DENIED;
1789 }
1790 }
1791 break;
1792 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001793 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1794 if (pid != selfPid) {
1795 // Ensure we're being called by system_server, or similar process with
1796 // permissions to notify the camera service about system events
1797 if (!checkCallingPermission(
1798 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1799 const int uid = getCallingUid();
1800 ALOGE("Permission Denial: cannot send updates to camera service about system"
1801 " events from pid=%d, uid=%d", pid, uid);
1802 return PERMISSION_DENIED;
1803 }
1804 }
1805 break;
1806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 }
1808
1809 return BnCameraService::onTransact(code, data, reply, flags);
1810}
1811
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812// We share the media players for shutter and recording sound for all clients.
1813// A reference count is kept to determine when we will actually release the
1814// media players.
1815
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001816MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001818 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001819 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 mp->prepare();
1821 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001822 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 return NULL;
1824 }
1825 return mp;
1826}
1827
1828void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001829 ATRACE_CALL();
1830
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 Mutex::Autolock lock(mSoundLock);
1832 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1833 if (mSoundRef++) return;
1834
1835 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1836 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1837}
1838
1839void CameraService::releaseSound() {
1840 Mutex::Autolock lock(mSoundLock);
1841 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1842 if (--mSoundRef) return;
1843
1844 for (int i = 0; i < NUM_SOUNDS; i++) {
1845 if (mSoundPlayer[i] != 0) {
1846 mSoundPlayer[i]->disconnect();
1847 mSoundPlayer[i].clear();
1848 }
1849 }
1850}
1851
1852void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001853 ATRACE_CALL();
1854
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 LOG1("playSound(%d)", kind);
1856 Mutex::Autolock lock(mSoundLock);
1857 sp<MediaPlayer> player = mSoundPlayer[kind];
1858 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001859 player->seekTo(0);
1860 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 }
1862}
1863
1864// ----------------------------------------------------------------------------
1865
1866CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001867 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001868 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001869 int cameraId, int cameraFacing,
1870 int clientPid, uid_t clientUid,
1871 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001872 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001873 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001874 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001875 cameraId, cameraFacing,
1876 clientPid, clientUid,
1877 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001878{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001880 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001882 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001885
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001886 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887}
1888
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889// tear down the client
1890CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001891 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001892 mDestructionStarted = true;
1893
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001894 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001895 // unconditionally disconnect. function is idempotent
1896 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897}
1898
Igor Murashkin634a5152013-02-20 17:15:11 -08001899CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001900 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001901 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001902 int cameraId, int cameraFacing,
1903 int clientPid, uid_t clientUid,
1904 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001905 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001906{
1907 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001908 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001909 mCameraId = cameraId;
1910 mCameraFacing = cameraFacing;
1911 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001912 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001913 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001914 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001915 mDestructionStarted = false;
1916}
1917
1918CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001919 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001920 mDestructionStarted = true;
1921}
1922
1923void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001924 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001925 return;
1926 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001927 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001928
1929 mCameraService->removeByClient(this);
1930 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001931 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001932
1933 sp<IBinder> remote = getRemote();
1934 if (remote != nullptr) {
1935 remote->unlinkToDeath(mCameraService);
1936 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001937
1938 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001939 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1940
Igor Murashkincba2c162013-03-20 15:56:31 -07001941 // client shouldn't be able to call into us anymore
1942 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001943}
1944
Ruben Brunkcc776712015-02-17 20:18:47 -08001945String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001946 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001947}
1948
1949
1950int CameraService::BasicClient::getClientPid() const {
1951 return mClientPid;
1952}
1953
Ruben Brunk6267b532015-04-30 17:44:07 -07001954uid_t CameraService::BasicClient::getClientUid() const {
1955 return mClientUid;
1956}
1957
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001958bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1959 // Defaults to API2.
1960 return level == API_2;
1961}
1962
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001963status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001964 ATRACE_CALL();
1965
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001966 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001967 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001968 mOpsCallback = new OpsCallback(this);
1969
Igor Murashkine6800ce2013-03-04 17:25:57 -08001970 {
1971 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001972 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001973 }
1974
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001975 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001976 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001977 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001978 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001979
Svetoslav28e8ef72015-05-11 19:21:31 -07001980 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001981 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001982 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001983 return PERMISSION_DENIED;
1984 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001985
Svetoslav28e8ef72015-05-11 19:21:31 -07001986 if (res == AppOpsManager::MODE_IGNORED) {
1987 ALOGI("Camera %d: Access for \"%s\" has been restricted",
1988 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07001989 // Return the same error as for device policy manager rejection
1990 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07001991 }
1992
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001993 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001994
1995 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1996 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001997 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001998
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07001999 // Transition device state to OPEN
2000 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2001 String8::format("%d", mCameraId));
2002
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002003 return OK;
2004}
2005
2006status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002007 ATRACE_CALL();
2008
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002009 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002010 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002011 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002012 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002013 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002014 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002015
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2017 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002018
Ruben Brunkcc776712015-02-17 20:18:47 -08002019 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002020 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002021 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002022
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002023 // Transition device state to CLOSED
2024 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2025 String8::format("%d", mCameraId));
2026
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002027 // Notify flashlight that a camera device is closed.
2028 mCameraService->mFlashlight->deviceClosed(
2029 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002030 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002031 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002032 if (mOpsCallback != NULL) {
2033 mAppOpsManager.stopWatchingMode(mOpsCallback);
2034 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002035 mOpsCallback.clear();
2036
2037 return OK;
2038}
2039
2040void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002041 ATRACE_CALL();
2042
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002043 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002044 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002045
2046 if (op != AppOpsManager::OP_CAMERA) {
2047 ALOGW("Unexpected app ops notification received: %d", op);
2048 return;
2049 }
2050
2051 int32_t res;
2052 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002053 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002054 ALOGV("checkOp returns: %d, %s ", res,
2055 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2056 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2057 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2058 "UNKNOWN");
2059
2060 if (res != AppOpsManager::MODE_ALLOWED) {
2061 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2062 myName.string());
2063 // Reset the client PID to allow server-initiated disconnect,
2064 // and to prevent further calls by client.
2065 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002066 CaptureResultExtras resultExtras; // a dummy result (invalid)
2067 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002068 disconnect();
2069 }
2070}
2071
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072// ----------------------------------------------------------------------------
2073
Ruben Brunkcc776712015-02-17 20:18:47 -08002074// Provide client strong pointer for callbacks.
2075sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2076 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2077 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2078 if (clientDescriptor != nullptr) {
2079 return sp<Client>{
2080 static_cast<Client*>(clientDescriptor->getValue().get())};
2081 }
2082 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083}
2084
Jianing Weicb0652e2014-03-12 18:29:36 -07002085void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2086 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002087 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002088}
2089
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002090// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002091void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002092 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002093 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002094}
2095
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002096bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2097 return level == API_1;
2098}
2099
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002100CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2101 mClient(client) {
2102}
2103
2104void CameraService::Client::OpsCallback::opChanged(int32_t op,
2105 const String16& packageName) {
2106 sp<BasicClient> client = mClient.promote();
2107 if (client != NULL) {
2108 client->opChanged(op, packageName);
2109 }
2110}
2111
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002113// CameraState
2114// ----------------------------------------------------------------------------
2115
2116CameraService::CameraState::CameraState(const String8& id, int cost,
2117 const std::set<String8>& conflicting) : mId(id),
2118 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2119
2120CameraService::CameraState::~CameraState() {}
2121
2122ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2123 Mutex::Autolock lock(mStatusLock);
2124 return mStatus;
2125}
2126
2127CameraParameters CameraService::CameraState::getShimParams() const {
2128 return mShimParams;
2129}
2130
2131void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2132 mShimParams = params;
2133}
2134
2135int CameraService::CameraState::getCost() const {
2136 return mCost;
2137}
2138
2139std::set<String8> CameraService::CameraState::getConflicting() const {
2140 return mConflicting;
2141}
2142
2143String8 CameraService::CameraState::getId() const {
2144 return mId;
2145}
2146
2147// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002148// ClientEventListener
2149// ----------------------------------------------------------------------------
2150
2151void CameraService::ClientEventListener::onClientAdded(
2152 const resource_policy::ClientDescriptor<String8,
2153 sp<CameraService::BasicClient>>& descriptor) {
2154 auto basicClient = descriptor.getValue();
2155 if (basicClient.get() != nullptr) {
2156 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2157 notifier.noteStartCamera(descriptor.getKey(),
2158 static_cast<int>(basicClient->getClientUid()));
2159 }
2160}
2161
2162void CameraService::ClientEventListener::onClientRemoved(
2163 const resource_policy::ClientDescriptor<String8,
2164 sp<CameraService::BasicClient>>& descriptor) {
2165 auto basicClient = descriptor.getValue();
2166 if (basicClient.get() != nullptr) {
2167 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2168 notifier.noteStopCamera(descriptor.getKey(),
2169 static_cast<int>(basicClient->getClientUid()));
2170 }
2171}
2172
2173
2174// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002175// CameraClientManager
2176// ----------------------------------------------------------------------------
2177
Ruben Brunk99e69712015-05-26 17:25:07 -07002178CameraService::CameraClientManager::CameraClientManager() {
2179 setListener(std::make_shared<ClientEventListener>());
2180}
2181
Ruben Brunkcc776712015-02-17 20:18:47 -08002182CameraService::CameraClientManager::~CameraClientManager() {}
2183
2184sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2185 const String8& id) const {
2186 auto descriptor = get(id);
2187 if (descriptor == nullptr) {
2188 return sp<BasicClient>{nullptr};
2189 }
2190 return descriptor->getValue();
2191}
2192
2193String8 CameraService::CameraClientManager::toString() const {
2194 auto all = getAll();
2195 String8 ret("[");
2196 bool hasAny = false;
2197 for (auto& i : all) {
2198 hasAny = true;
2199 String8 key = i->getKey();
2200 int32_t cost = i->getCost();
2201 int32_t pid = i->getOwnerId();
2202 int32_t priority = i->getPriority();
2203 auto conflicting = i->getConflicting();
2204 auto clientSp = i->getValue();
2205 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002206 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002207 if (clientSp.get() != nullptr) {
2208 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002209 uid_t clientUid = clientSp->getClientUid();
2210 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002211 }
2212 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2213 PRId32 ", ", key.string(), cost, pid, priority);
2214
Ruben Brunk6267b532015-04-30 17:44:07 -07002215 if (clientSp.get() != nullptr) {
2216 ret.appendFormat("User Id: %d, ", clientUserId);
2217 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002218 if (packageName.size() != 0) {
2219 ret.appendFormat("Client Package Name: %s", packageName.string());
2220 }
2221
2222 ret.append(", Conflicting Client Devices: {");
2223 for (auto& j : conflicting) {
2224 ret.appendFormat("%s, ", j.string());
2225 }
2226 ret.append("})");
2227 }
2228 if (hasAny) ret.append("\n");
2229 ret.append("]\n");
2230 return ret;
2231}
2232
2233CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2234 const String8& key, const sp<BasicClient>& value, int32_t cost,
2235 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2236
2237 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2238 key, value, cost, conflictingKeys, priority, ownerId);
2239}
2240
2241CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2242 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2243 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2244 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2245}
2246
2247// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248
2249static const int kDumpLockRetries = 50;
2250static const int kDumpLockSleep = 60000;
2251
2252static bool tryLock(Mutex& mutex)
2253{
2254 bool locked = false;
2255 for (int i = 0; i < kDumpLockRetries; ++i) {
2256 if (mutex.tryLock() == NO_ERROR) {
2257 locked = true;
2258 break;
2259 }
2260 usleep(kDumpLockSleep);
2261 }
2262 return locked;
2263}
2264
2265status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002266 ATRACE_CALL();
2267
Ruben Brunka8ca9152015-04-07 14:23:40 -07002268 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002270 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271 "can't dump CameraService from pid=%d, uid=%d\n",
2272 getCallingPid(),
2273 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 write(fd, result.string(), result.size());
2275 } else {
2276 bool locked = tryLock(mServiceLock);
2277 // failed to lock - CameraService is probably deadlocked
2278 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002279 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002280 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 }
2282
2283 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002284 if (!mModule) {
2285 result = String8::format("No camera module available!\n");
2286 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002287
2288 // Dump event log for error information
2289 dumpEventLog(fd);
2290
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002291 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002292 return NO_ERROR;
2293 }
2294
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002295 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2296 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2297 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2298 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002299 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2300 String8 activeClientString = mActiveClientManager.toString();
2301 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002302 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002303
Ruben Brunkf81648e2014-04-17 16:14:57 -07002304 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2305 if (desc == NULL) {
2306 result.appendFormat("Vendor tags left unimplemented.\n");
2307 } else {
2308 result.appendFormat("Vendor tag definitions:\n");
2309 }
2310
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002311 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002312
2313 if (desc != NULL) {
2314 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2315 }
2316
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002317 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002318
2319 bool stateLocked = tryLock(mCameraStatesLock);
2320 if (!stateLocked) {
2321 result = String8::format("CameraStates in use, may be deadlocked\n");
2322 write(fd, result.string(), result.size());
2323 }
2324
2325 for (auto& state : mCameraStates) {
2326 String8 cameraId = state.first;
2327 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002328 camera_info info;
2329
Ruben Brunkcc776712015-02-17 20:18:47 -08002330 // TODO: Change getCameraInfo + HAL to use String cameraIds
2331 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002332 if (rc != OK) {
2333 result.appendFormat(" Error reading static information!\n");
2334 write(fd, result.string(), result.size());
2335 } else {
2336 result.appendFormat(" Facing: %s\n",
2337 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2338 result.appendFormat(" Orientation: %d\n", info.orientation);
2339 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002340 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002341 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2342 } else {
2343 deviceVersion = info.device_version;
2344 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002345
2346 auto conflicting = state.second->getConflicting();
2347 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2348 result.appendFormat(" Conflicting Devices:");
2349 for (auto& id : conflicting) {
2350 result.appendFormat(" %s", cameraId.string());
2351 }
2352 if (conflicting.size() == 0) {
2353 result.appendFormat(" NONE");
2354 }
2355 result.appendFormat("\n");
2356
2357 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002358 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2359 result.appendFormat(" Device static metadata:\n");
2360 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002361 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002362 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002363 } else {
2364 write(fd, result.string(), result.size());
2365 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002366
2367 CameraParameters p = state.second->getShimParams();
2368 if (!p.isEmpty()) {
2369 result = String8::format(" Camera1 API shim is using parameters:\n ");
2370 write(fd, result.string(), result.size());
2371 p.dump(fd, args);
2372 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002373 }
2374
Ruben Brunkcc776712015-02-17 20:18:47 -08002375 auto clientDescriptor = mActiveClientManager.get(cameraId);
2376 if (clientDescriptor == nullptr) {
2377 result = String8::format(" Device %s is closed, no client instance\n",
2378 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002379 write(fd, result.string(), result.size());
2380 continue;
2381 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002383 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2384 cameraId.string());
2385 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2386 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2387
2388 auto client = clientDescriptor->getValue();
2389 result.appendFormat("Client package: %s\n",
2390 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002391 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002392
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002393 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002395
2396 if (stateLocked) mCameraStatesLock.unlock();
2397
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002399 result = String8::format("\nNo active camera clients yet.\n");
2400 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 }
2402
2403 if (locked) mServiceLock.unlock();
2404
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002405 // Dump camera traces if there were any
2406 write(fd, "\n", 1);
2407 camera3::CameraTraces::dump(fd, args);
2408
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 // change logging level
2410 int n = args.size();
2411 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002412 String16 verboseOption("-v");
2413 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 String8 levelStr(args[i+1]);
2415 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002416 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002418 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 }
2420 }
2421 }
2422 return NO_ERROR;
2423}
2424
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002425void CameraService::dumpEventLog(int fd) {
2426 String8 result = String8("\nPrior client events (most recent at top):\n");
2427
2428 Mutex::Autolock l(mLogLock);
2429 for (const auto& msg : mEventLog) {
2430 result.appendFormat(" %s\n", msg.string());
2431 }
2432
2433 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2434 result.append(" ...\n");
2435 } else if (mEventLog.size() == 0) {
2436 result.append(" [no events yet]\n");
2437 }
2438 result.append("\n");
2439
2440 write(fd, result.string(), result.size());
2441}
2442
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002443void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002444 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002445 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2446 if (mTorchClientMap[i] == who) {
2447 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002448 String8 cameraId = mTorchClientMap.keyAt(i);
2449 status_t res = mFlashlight->setTorchMode(cameraId, false);
2450 if (res) {
2451 ALOGE("%s: torch client died but couldn't turn off torch: "
2452 "%s (%d)", __FUNCTION__, strerror(-res), res);
2453 return;
2454 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002455 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002456 break;
2457 }
2458 }
2459}
2460
Ruben Brunkcc776712015-02-17 20:18:47 -08002461/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002462
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002463 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002464 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2465 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002466 */
2467
Ruben Brunka8ca9152015-04-07 14:23:40 -07002468 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2469
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002470 // check torch client
2471 handleTorchClientBinderDied(who);
2472
2473 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002474 if(!evictClientIdByRemote(who)) {
2475 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002476 return;
2477 }
2478
Ruben Brunkcc776712015-02-17 20:18:47 -08002479 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2480 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002481}
2482
Ruben Brunkcc776712015-02-17 20:18:47 -08002483void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2484 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002485}
2486
Ruben Brunkcc776712015-02-17 20:18:47 -08002487void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2488 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2489 // Do not lock mServiceLock here or can get into a deadlock from
2490 // connect() -> disconnect -> updateStatus
2491
2492 auto state = getCameraState(cameraId);
2493
2494 if (state == nullptr) {
2495 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2496 cameraId.string());
2497 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002498 }
2499
Ruben Brunkcc776712015-02-17 20:18:47 -08002500 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2501 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2502 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2503 (const String8& cameraId, ICameraServiceListener::Status status) {
2504
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002505 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2506 // Update torch status if it has a flash unit.
2507 Mutex::Autolock al(mTorchStatusMutex);
2508 ICameraServiceListener::TorchStatus torchStatus;
2509 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2510 NAME_NOT_FOUND) {
2511 ICameraServiceListener::TorchStatus newTorchStatus =
2512 status == ICameraServiceListener::STATUS_PRESENT ?
2513 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2514 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2515 if (torchStatus != newTorchStatus) {
2516 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2517 }
2518 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002519 }
2520
2521 Mutex::Autolock lock(mStatusListenerLock);
2522
2523 for (auto& listener : mListenerList) {
2524 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2525 int id = cameraIdToInt(cameraId);
2526 if (id != -1) listener->onStatusChanged(status, id);
2527 }
2528 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002529}
2530
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002531void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2532 const String8& cameraId) {
2533 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2534 if (proxyBinder == nullptr) return;
2535 String16 id(cameraId);
2536 proxyBinder->notifyCameraState(id, newState);
2537}
2538
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002539status_t CameraService::getTorchStatusLocked(
2540 const String8& cameraId,
2541 ICameraServiceListener::TorchStatus *status) const {
2542 if (!status) {
2543 return BAD_VALUE;
2544 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002545 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2546 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002547 // invalid camera ID or the camera doesn't have a flash unit
2548 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002549 }
2550
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002551 *status = mTorchStatusMap.valueAt(index);
2552 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002553}
2554
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002555status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002556 ICameraServiceListener::TorchStatus status) {
2557 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2558 if (index == NAME_NOT_FOUND) {
2559 return BAD_VALUE;
2560 }
2561 ICameraServiceListener::TorchStatus& item =
2562 mTorchStatusMap.editValueAt(index);
2563 item = status;
2564
2565 return OK;
2566}
2567
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568}; // namespace android