blob: 897fa1b6b7cef59c760280490fe0991414366617 [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;
Yin-Chia Yeh6dd6c542015-12-07 12:20:11 -0800156 mNumberOfNormalCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700157 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700158 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800159
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700161 err = mModule->init();
162 if (err != OK) {
163 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
164 strerror(-err));
165 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800166
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700167 mNumberOfCameras = 0;
168 delete mModule;
169 mModule = nullptr;
170 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700171 }
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700172 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700173
174 mNumberOfCameras = mModule->getNumberOfCameras();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700175 mNumberOfNormalCameras = mNumberOfCameras;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700176
Yin-Chia Yehd4a653a2015-10-14 11:05:44 -0700177 // Setup vendor tags before we call get_camera_info the first time
178 // because HAL might need to setup static vendor keys in get_camera_info
179 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
180 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
181 setUpVendorTags();
182 }
183
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700184 mFlashlight = new CameraFlashlight(*mModule, *this);
185 status_t res = mFlashlight->findFlashUnits();
186 if (res) {
187 // impossible because we haven't open any camera devices.
188 ALOGE("Failed to find flash units.");
189 }
190
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700191 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700192 for (int i = 0; i < mNumberOfCameras; i++) {
193 String8 cameraId = String8::format("%d", i);
194
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700195 // Get camera info
196
197 struct camera_info info;
198 bool haveInfo = true;
199 status_t rc = mModule->getCameraInfo(i, &info);
200 if (rc != NO_ERROR) {
201 ALOGE("%s: Received error loading camera info for device %d, cost and"
202 " conflicting devices fields set to defaults for this device.",
203 __FUNCTION__, i);
204 haveInfo = false;
205 }
206
207 // Check for backwards-compatibility support
208 if (haveInfo) {
209 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
210 delete mModule;
211 mModule = nullptr;
212 return;
213 }
214 }
215
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700216 // Defaults to use for cost and conflicting devices
217 int cost = 100;
218 char** conflicting_devices = nullptr;
219 size_t conflicting_devices_length = 0;
220
221 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700222 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
223 cost = info.resource_cost;
224 conflicting_devices = info.conflicting_devices;
225 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700226 }
227
228 std::set<String8> conflicting;
229 for (size_t i = 0; i < conflicting_devices_length; i++) {
230 conflicting.emplace(String8(conflicting_devices[i]));
231 }
232
233 // Initialize state for each camera device
234 {
235 Mutex::Autolock lock(mCameraStatesLock);
236 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
237 conflicting));
238 }
239
240 if (mFlashlight->hasFlashUnit(cameraId)) {
241 mTorchStatusMap.add(cameraId,
242 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
243 }
244 }
245
246 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
247 mModule->setCallbacks(this);
248 }
249
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700250 CameraDeviceFactory::registerService(this);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700251
252 CameraService::pingCameraServiceProxy();
253}
254
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700255sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Ruben Brunk2823ce02015-05-19 17:25:13 -0700256 sp<IServiceManager> sm = defaultServiceManager();
257 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
258 if (binder == nullptr) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700259 return nullptr;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700260 }
261 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700262 return proxyBinder;
263}
264
265void CameraService::pingCameraServiceProxy() {
266 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
267 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700268 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700269}
270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800272 if (mModule) {
273 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800274 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800275 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800276 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800277 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700278}
279
Ruben Brunkcc776712015-02-17 20:18:47 -0800280void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
281 camera_device_status_t newStatus) {
282 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700283 cameraId, newStatus);
284
Ruben Brunkcc776712015-02-17 20:18:47 -0800285 String8 id = String8::format("%d", cameraId);
286 std::shared_ptr<CameraState> state = getCameraState(id);
287
288 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700289 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
290 return;
291 }
292
Ruben Brunkcc776712015-02-17 20:18:47 -0800293 ICameraServiceListener::Status oldStatus = state->getStatus();
294
295 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
296 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700297 return;
298 }
299
Igor Murashkincba2c162013-03-20 15:56:31 -0700300 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700301 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
302 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800303 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700304 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800305 // Don't do this in updateStatus to avoid deadlock over mServiceLock
306 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700307
Ruben Brunkcc776712015-02-17 20:18:47 -0800308 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
309 // to this device until the status changes
310 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700311
Ruben Brunkcc776712015-02-17 20:18:47 -0800312 // Remove cached shim parameters
313 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700314
Ruben Brunkcc776712015-02-17 20:18:47 -0800315 // Remove the client from the list of active clients
316 clientToDisconnect = removeClientLocked(id);
317
318 // Notify the client of disconnection
Tom Keel5adc76c2015-10-08 16:42:56 +0200319 if (clientToDisconnect != nullptr) {
320 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
321 CaptureResultExtras{});
322 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700323 }
324
Ruben Brunkcc776712015-02-17 20:18:47 -0800325 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
326 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700327
Ruben Brunkcc776712015-02-17 20:18:47 -0800328 // Disconnect client
329 if (clientToDisconnect.get() != nullptr) {
330 // Ensure not in binder RPC so client disconnect PID checks work correctly
331 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
332 "onDeviceStatusChanged must be called from the camera service process!");
333 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700334 }
335
Ruben Brunkcc776712015-02-17 20:18:47 -0800336 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700337 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
338 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
339 newStatus));
340 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800341 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700342 }
343
Igor Murashkincba2c162013-03-20 15:56:31 -0700344}
345
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800346void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800347 ICameraServiceListener::TorchStatus newStatus) {
348 Mutex::Autolock al(mTorchStatusMutex);
349 onTorchStatusChangedLocked(cameraId, newStatus);
350}
351
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800352void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800353 ICameraServiceListener::TorchStatus newStatus) {
354 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
355 __FUNCTION__, cameraId.string(), newStatus);
356
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800357 ICameraServiceListener::TorchStatus status;
358 status_t res = getTorchStatusLocked(cameraId, &status);
359 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700360 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
361 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800362 return;
363 }
364 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800365 return;
366 }
367
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800368 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800369 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700370 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800371 return;
372 }
373
Ruben Brunkcc776712015-02-17 20:18:47 -0800374 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700375 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700376 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700377 auto iter = mTorchUidMap.find(cameraId);
378 if (iter != mTorchUidMap.end()) {
379 int oldUid = iter->second.second;
380 int newUid = iter->second.first;
381 BatteryNotifier& notifier(BatteryNotifier::getInstance());
382 if (oldUid != newUid) {
383 // If the UID has changed, log the status and update current UID in mTorchUidMap
384 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
385 notifier.noteFlashlightOff(cameraId, oldUid);
386 }
387 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
388 notifier.noteFlashlightOn(cameraId, newUid);
389 }
390 iter->second.second = newUid;
391 } else {
392 // If the UID has not changed, log the status
393 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
394 notifier.noteFlashlightOn(cameraId, oldUid);
395 } else {
396 notifier.noteFlashlightOff(cameraId, oldUid);
397 }
398 }
399 }
400 }
401
402 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800403 Mutex::Autolock lock(mStatusListenerLock);
404 for (auto& i : mListenerList) {
405 i->onTorchStatusChanged(newStatus, String16{cameraId});
406 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800407 }
408}
409
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700411 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700412 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
413}
414
415int32_t CameraService::getNumberOfCameras(int type) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700416 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700417 switch (type) {
418 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
419 return mNumberOfNormalCameras;
420 case CAMERA_TYPE_ALL:
421 return mNumberOfCameras;
422 default:
423 ALOGW("%s: Unknown camera type %d, returning 0",
424 __FUNCTION__, type);
425 return 0;
426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427}
428
429status_t CameraService::getCameraInfo(int cameraId,
430 struct CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700431 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700432 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700433 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700434 }
435
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
437 return BAD_VALUE;
438 }
439
Iliyan Malchev8951a972011-04-14 16:55:59 -0700440 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700441 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800442 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700443 cameraInfo->facing = info.facing;
444 cameraInfo->orientation = info.orientation;
445 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446}
447
Ruben Brunkcc776712015-02-17 20:18:47 -0800448int CameraService::cameraIdToInt(const String8& cameraId) {
449 errno = 0;
450 size_t pos = 0;
451 int ret = stoi(std::string{cameraId.string()}, &pos);
452 if (errno != 0 || pos != cameraId.size()) {
453 return -1;
454 }
455 return ret;
456}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700457
458status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700459 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700460 status_t ret = OK;
461 struct CameraInfo info;
462 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
463 return ret;
464 }
465
466 CameraMetadata shimInfo;
467 int32_t orientation = static_cast<int32_t>(info.orientation);
468 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
469 return ret;
470 }
471
472 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
473 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
474 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
475 return ret;
476 }
477
Igor Murashkin65d14b92014-06-17 12:03:20 -0700478 CameraParameters shimParams;
479 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
480 // Error logged by callee
481 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700482 }
483
484 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700485 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700486 Vector<int32_t> formats;
487 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700488 {
489 shimParams.getSupportedPreviewSizes(/*out*/sizes);
490 shimParams.getSupportedPreviewFormats(/*out*/formats);
491 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700492 }
493
494 // Always include IMPLEMENTATION_DEFINED
495 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
496
497 const size_t INTS_PER_CONFIG = 4;
498
499 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700500 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
501
502 Vector<int32_t> streamConfigs;
503 streamConfigs.setCapacity(streamConfigSize);
504
Ruben Brunkb2119af2014-05-09 19:57:56 -0700505 for (size_t i = 0; i < formats.size(); ++i) {
506 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700507 streamConfigs.add(formats[i]);
508 streamConfigs.add(sizes[j].width);
509 streamConfigs.add(sizes[j].height);
510 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700511 }
512 }
513
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700514 for (size_t i = 0; i < jpegSizes.size(); ++i) {
515 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
516 streamConfigs.add(jpegSizes[i].width);
517 streamConfigs.add(jpegSizes[i].height);
518 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
519 }
520
Ruben Brunkb2119af2014-05-09 19:57:56 -0700521 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700522 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700523 return ret;
524 }
525
526 int64_t fakeMinFrames[0];
527 // TODO: Fixme, don't fake min frame durations.
528 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
529 fakeMinFrames, 0)) != OK) {
530 return ret;
531 }
532
533 int64_t fakeStalls[0];
534 // TODO: Fixme, don't fake stall durations.
535 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
536 fakeStalls, 0)) != OK) {
537 return ret;
538 }
539
540 *cameraInfo = shimInfo;
541 return OK;
542}
543
Zhijun He2b59be82013-09-25 10:14:30 -0700544status_t CameraService::getCameraCharacteristics(int cameraId,
545 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700546 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700547 if (!cameraInfo) {
548 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
549 return BAD_VALUE;
550 }
551
552 if (!mModule) {
553 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
554 return -ENODEV;
555 }
556
Zhijun He2b59be82013-09-25 10:14:30 -0700557 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
558 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
559 return BAD_VALUE;
560 }
561
562 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700563 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800564 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700565 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
566 /**
567 * Backwards compatibility mode for old HALs:
568 * - Convert CameraInfo into static CameraMetadata properties.
569 * - Retrieve cached CameraParameters for this camera. If none exist,
570 * attempt to open CameraClient and retrieve the CameraParameters.
571 * - Convert cached CameraParameters into static CameraMetadata
572 * properties.
573 */
574 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700575
Ruben Brunkb2119af2014-05-09 19:57:56 -0700576 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
577 return ret;
578 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700579
Ruben Brunkb2119af2014-05-09 19:57:56 -0700580 } else {
581 /**
582 * Normal HAL 2.1+ codepath.
583 */
584 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800585 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700586 *cameraInfo = info.static_camera_characteristics;
587 }
Zhijun He2b59be82013-09-25 10:14:30 -0700588
589 return ret;
590}
591
Ruben Brunkcc776712015-02-17 20:18:47 -0800592int CameraService::getCallingPid() {
593 return IPCThreadState::self()->getCallingPid();
594}
595
596int CameraService::getCallingUid() {
597 return IPCThreadState::self()->getCallingUid();
598}
599
600String8 CameraService::getFormattedCurrentTime() {
601 time_t now = time(nullptr);
602 char formattedTime[64];
603 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
604 return String8(formattedTime);
605}
606
607int CameraService::getCameraPriorityFromProcState(int procState) {
608 // Find the priority for the camera usage based on the process state. Higher priority clients
609 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700610 if (procState < 0) {
611 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
612 procState);
613 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800614 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700615 // Treat sleeping TOP processes the same as regular TOP processes, for
616 // access priority. This is important for lock-screen camera launch scenarios
617 if (procState == PROCESS_STATE_TOP_SLEEPING) {
618 procState = PROCESS_STATE_TOP;
619 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700620 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800621}
622
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800623status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700624 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800625 if (!mModule) {
626 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
627 return -ENODEV;
628 }
629
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800630 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
631 return OK;
632}
633
Igor Murashkin634a5152013-02-20 17:15:11 -0800634int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700635 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800636 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800637 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800638 return -1;
639 }
640
641 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800642 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800643 deviceVersion = info.device_version;
644 } else {
645 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
646 }
647
648 if (facing) {
649 *facing = info.facing;
650 }
651
652 return deviceVersion;
653}
654
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700655status_t CameraService::filterGetInfoErrorCode(status_t err) {
656 switch(err) {
657 case NO_ERROR:
658 case -EINVAL:
659 return err;
660 default:
661 break;
662 }
663 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800664}
665
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800666bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700667 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800668 vendor_tag_ops_t vOps = vendor_tag_ops_t();
669
670 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800671 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800672 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
673 return false;
674 }
675
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800676 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800677
678 // Ensure all vendor operations are present
679 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
680 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
681 vOps.get_tag_type == NULL) {
682 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
683 , __FUNCTION__);
684 return false;
685 }
686
687 // Read all vendor tag definitions into a descriptor
688 sp<VendorTagDescriptor> desc;
689 status_t res;
690 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
691 != OK) {
692 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
693 "received error %s (%d). Camera clients will not be able to use"
694 "vendor tags", __FUNCTION__, strerror(res), res);
695 return false;
696 }
697
698 // Set the global descriptor to use with camera metadata
699 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
700 return true;
701}
702
Ruben Brunkcc776712015-02-17 20:18:47 -0800703status_t CameraService::makeClient(const sp<CameraService>& cameraService,
704 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
705 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
706 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
707 /*out*/sp<BasicClient>* client) {
708
709 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
710 int id = cameraIdToInt(cameraId);
711 if (id == -1) {
712 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
713 cameraId.string());
714 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700715 }
716
Ruben Brunkcc776712015-02-17 20:18:47 -0800717 if (halVersion < 0 || halVersion == deviceVersion) {
718 // Default path: HAL version is unspecified by caller, create CameraClient
719 // based on device version reported by the HAL.
720 switch(deviceVersion) {
721 case CAMERA_DEVICE_API_VERSION_1_0:
722 if (effectiveApiLevel == API_1) { // Camera1 API route
723 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
724 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
725 clientPid, clientUid, getpid(), legacyMode);
726 } else { // Camera2 API route
727 ALOGW("Camera using old HAL version: %d", deviceVersion);
728 return -EOPNOTSUPP;
729 }
730 break;
731 case CAMERA_DEVICE_API_VERSION_2_0:
732 case CAMERA_DEVICE_API_VERSION_2_1:
733 case CAMERA_DEVICE_API_VERSION_3_0:
734 case CAMERA_DEVICE_API_VERSION_3_1:
735 case CAMERA_DEVICE_API_VERSION_3_2:
736 case CAMERA_DEVICE_API_VERSION_3_3:
737 if (effectiveApiLevel == API_1) { // Camera1 API route
738 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
739 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
740 clientPid, clientUid, servicePid, legacyMode);
741 } else { // Camera2 API route
742 sp<ICameraDeviceCallbacks> tmp =
743 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
744 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
745 facing, clientPid, clientUid, servicePid);
746 }
747 break;
748 default:
749 // Should not be reachable
750 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
751 return INVALID_OPERATION;
752 }
753 } else {
754 // A particular HAL version is requested by caller. Create CameraClient
755 // based on the requested HAL version.
756 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
757 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
758 // Only support higher HAL version device opened as HAL1.0 device.
759 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
760 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
761 clientPid, clientUid, servicePid, legacyMode);
762 } else {
763 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
764 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
765 " opened as HAL %x device", halVersion, deviceVersion,
766 CAMERA_DEVICE_API_VERSION_1_0);
767 return INVALID_OPERATION;
768 }
769 }
770 return NO_ERROR;
771}
772
Ruben Brunk6267b532015-04-30 17:44:07 -0700773String8 CameraService::toString(std::set<userid_t> intSet) {
774 String8 s("");
775 bool first = true;
776 for (userid_t i : intSet) {
777 if (first) {
778 s.appendFormat("%d", i);
779 first = false;
780 } else {
781 s.appendFormat(", %d", i);
782 }
783 }
784 return s;
785}
786
Ruben Brunkcc776712015-02-17 20:18:47 -0800787status_t CameraService::initializeShimMetadata(int cameraId) {
788 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700789
790 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800791 String8 id = String8::format("%d", cameraId);
792 status_t ret = NO_ERROR;
793 sp<Client> tmp = nullptr;
794 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
795 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
796 false, true, tmp)) != NO_ERROR) {
797 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
798 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700799 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800800 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700801}
802
Igor Murashkin65d14b92014-06-17 12:03:20 -0700803status_t CameraService::getLegacyParametersLazy(int cameraId,
804 /*out*/
805 CameraParameters* parameters) {
806
807 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
808
809 status_t ret = 0;
810
811 if (parameters == NULL) {
812 ALOGE("%s: parameters must not be null", __FUNCTION__);
813 return BAD_VALUE;
814 }
815
Ruben Brunkcc776712015-02-17 20:18:47 -0800816 String8 id = String8::format("%d", cameraId);
817
818 // Check if we already have parameters
819 {
820 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700821 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800822 auto cameraState = getCameraState(id);
823 if (cameraState == nullptr) {
824 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
825 return BAD_VALUE;
826 }
827 CameraParameters p = cameraState->getShimParams();
828 if (!p.isEmpty()) {
829 *parameters = p;
830 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700831 }
832 }
833
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 int64_t token = IPCThreadState::self()->clearCallingIdentity();
835 ret = initializeShimMetadata(cameraId);
836 IPCThreadState::self()->restoreCallingIdentity(token);
837 if (ret != NO_ERROR) {
838 // Error already logged by callee
839 return ret;
840 }
841
842 // Check for parameters again
843 {
844 // Scope for service lock
845 Mutex::Autolock lock(mServiceLock);
846 auto cameraState = getCameraState(id);
847 if (cameraState == nullptr) {
848 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
849 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700850 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800851 CameraParameters p = cameraState->getShimParams();
852 if (!p.isEmpty()) {
853 *parameters = p;
854 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700855 }
856 }
857
Ruben Brunkcc776712015-02-17 20:18:47 -0800858 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
859 __FUNCTION__);
860 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700861}
862
Ruben Brunk36597b22015-03-20 22:15:57 -0700863status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
864 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800865
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500867
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800868 if (clientUid == USE_CALLING_UID) {
869 clientUid = getCallingUid();
870 } else {
871 // We only trust our own process to forward client UIDs
872 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700873 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
874 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700875 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800876 }
877 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700878
Iliyan Malchev8951a972011-04-14 16:55:59 -0700879 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800880 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
881 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700882 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700883 }
884
Ruben Brunkcc776712015-02-17 20:18:47 -0800885 if (getCameraState(cameraId) == nullptr) {
886 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
887 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700888 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 }
890
Ruben Brunkcc776712015-02-17 20:18:47 -0800891 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800892 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800893 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700894 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800895 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
896 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800897 if (strcmp(value, "1") == 0) {
898 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800899 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
900 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700901 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800902 }
903
Ruben Brunka8ca9152015-04-07 14:23:40 -0700904 // Only allow clients who are being used by the current foreground device user, unless calling
905 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700906 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
907 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
908 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
909 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700910 return PERMISSION_DENIED;
911 }
912
Ruben Brunkcc776712015-02-17 20:18:47 -0800913 return checkIfDeviceIsUsable(cameraId);
914}
915
916status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
917 auto cameraState = getCameraState(cameraId);
918 int callingPid = getCallingPid();
919 if (cameraState == nullptr) {
920 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
921 cameraId.string());
922 return -ENODEV;
923 }
924
925 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700926 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800927 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
928 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700929 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700930 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800931 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
932 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700933 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700934 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700935
Ruben Brunkcc776712015-02-17 20:18:47 -0800936 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800937}
938
Ruben Brunkcc776712015-02-17 20:18:47 -0800939void CameraService::finishConnectLocked(const sp<BasicClient>& client,
940 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800941
Ruben Brunkcc776712015-02-17 20:18:47 -0800942 // Make a descriptor for the incoming client
943 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
944 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
945
946 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
947 String8(client->getPackageName()));
948
949 if (evicted.size() > 0) {
950 // This should never happen - clients should already have been removed in disconnect
951 for (auto& i : evicted) {
952 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
953 __FUNCTION__, i->getKey().string());
954 }
955
956 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
957 __FUNCTION__);
958 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700959
960 // And register a death notification for the client callback. Do
961 // this last to avoid Binder policy where a nested Binder
962 // transaction might be pre-empted to service the client death
963 // notification if the client process dies before linkToDeath is
964 // invoked.
965 sp<IBinder> remoteCallback = client->getRemote();
966 if (remoteCallback != nullptr) {
967 remoteCallback->linkToDeath(this);
968 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800969}
970
971status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
972 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
973 /*out*/
974 sp<BasicClient>* client,
975 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700976 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800977 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700978 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800979 DescriptorPtr clientDescriptor;
980 {
981 if (effectiveApiLevel == API_1) {
982 // If we are using API1, any existing client for this camera ID with the same remote
983 // should be returned rather than evicted to allow MediaRecorder to work properly.
984
985 auto current = mActiveClientManager.get(cameraId);
986 if (current != nullptr) {
987 auto clientSp = current->getValue();
988 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700989 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
990 ALOGW("CameraService connect called from same client, but with a different"
991 " API level, evicting prior client...");
992 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800993 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700994 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800995 *client = clientSp;
996 return NO_ERROR;
997 }
998 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800999 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001000 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001001
Ruben Brunkcc776712015-02-17 20:18:47 -08001002 // Return error if the device was unplugged or removed by the HAL for some reason
1003 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1004 return ret;
1005 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001006
Ruben Brunkcc776712015-02-17 20:18:47 -08001007 // Get current active client PIDs
1008 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1009 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001010
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001011 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1012 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1013 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1014 // not have an out-of-class definition.
1015 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001016
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 // Get priorites of all active PIDs
1018 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1019 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001020
Ruben Brunkcc776712015-02-17 20:18:47 -08001021 // Update all active clients' priorities
1022 std::map<int,int> pidToPriorityMap;
1023 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1024 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1025 }
1026 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001027
Ruben Brunkcc776712015-02-17 20:18:47 -08001028 // Get state for the given cameraId
1029 auto state = getCameraState(cameraId);
1030 if (state == nullptr) {
1031 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1032 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001033 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001034 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001035
1036 // Make descriptor for incoming client
1037 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1038 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1039 state->getConflicting(),
1040 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1041
1042 // Find clients that would be evicted
1043 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1044
1045 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1046 // background, so we cannot do evictions
1047 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1048 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1049 " priority).", clientPid);
1050
1051 sp<BasicClient> clientSp = clientDescriptor->getValue();
1052 String8 curTime = getFormattedCurrentTime();
1053 auto incompatibleClients =
1054 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1055
1056 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001057 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001058 cameraId.string(), packageName.string(), clientPid,
1059 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1060
1061 for (auto& i : incompatibleClients) {
1062 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1063 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1064 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1065 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001066 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1067 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1068 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1069 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001070 }
1071
1072 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001073 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001074 mEventLog.add(msg);
1075
1076 return -EBUSY;
1077 }
1078
1079 for (auto& i : evicted) {
1080 sp<BasicClient> clientSp = i->getValue();
1081 if (clientSp.get() == nullptr) {
1082 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1083
1084 // TODO: Remove this
1085 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1086 __FUNCTION__);
1087 mActiveClientManager.remove(i);
1088 continue;
1089 }
1090
1091 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1092 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001093 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001094
Ruben Brunkcc776712015-02-17 20:18:47 -08001095 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001096 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1097 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1098 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001099 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1100 i->getOwnerId(), i->getPriority(), cameraId.string(),
1101 packageName.string(), clientPid,
1102 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1103
1104 // Notify the client of disconnection
1105 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1106 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001107 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001108 }
1109
Ruben Brunkcc776712015-02-17 20:18:47 -08001110 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1111 // other clients from connecting in mServiceLockWrapper if held
1112 mServiceLock.unlock();
1113
1114 // Clear caller identity temporarily so client disconnect PID checks work correctly
1115 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1116
1117 // Destroy evicted clients
1118 for (auto& i : evictedClients) {
1119 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001120 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001121 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001122
1123 IPCThreadState::self()->restoreCallingIdentity(token);
1124
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001125 for (const auto& i : evictedClients) {
1126 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1127 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1128 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1129 if (ret == TIMED_OUT) {
1130 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1131 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1132 mActiveClientManager.toString().string());
1133 return -EBUSY;
1134 }
1135 if (ret != NO_ERROR) {
1136 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1137 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1138 ret, mActiveClientManager.toString().string());
1139 return ret;
1140 }
1141 }
1142
1143 evictedClients.clear();
1144
Ruben Brunkcc776712015-02-17 20:18:47 -08001145 // Once clients have been disconnected, relock
1146 mServiceLock.lock();
1147
1148 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1149 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1150 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001151 }
1152
Ruben Brunkcc776712015-02-17 20:18:47 -08001153 *partial = clientDescriptor;
1154 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001155}
1156
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001157status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001158 const sp<ICameraClient>& cameraClient,
1159 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001160 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001161 int clientUid,
1162 /*out*/
1163 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001164
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001165 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001166 status_t ret = NO_ERROR;
1167 String8 id = String8::format("%d", cameraId);
1168 sp<Client> client = nullptr;
1169 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001170 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001171
Ruben Brunkcc776712015-02-17 20:18:47 -08001172 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001173 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001174 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001175 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176 }
1177
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001178 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001179 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180}
1181
Zhijun Heb10cdad2014-06-16 16:38:35 -07001182status_t CameraService::connectLegacy(
1183 const sp<ICameraClient>& cameraClient,
1184 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001185 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001186 int clientUid,
1187 /*out*/
1188 sp<ICamera>& device) {
1189
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001190 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001191 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001192 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001193 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001194 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001195 /*
1196 * Either the HAL version is unspecified in which case this just creates
1197 * a camera client selected by the latest device version, or
1198 * it's a particular version in which case the HAL must supported
1199 * the open_legacy call
1200 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001201 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001202 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001203 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001204 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001205 return INVALID_OPERATION;
1206 }
1207
Ruben Brunkcc776712015-02-17 20:18:47 -08001208 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001209 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001210 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001212
Ruben Brunkcc776712015-02-17 20:18:47 -08001213 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001214 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001215 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001216 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001217 }
1218
Zhijun Heb10cdad2014-06-16 16:38:35 -07001219 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001220 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001221}
1222
Ruben Brunkcc776712015-02-17 20:18:47 -08001223status_t CameraService::connectDevice(
1224 const sp<ICameraDeviceCallbacks>& cameraCb,
1225 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001226 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001227 int clientUid,
1228 /*out*/
1229 sp<ICameraDeviceUser>& device) {
1230
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001231 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001232 status_t ret = NO_ERROR;
1233 String8 id = String8::format("%d", cameraId);
1234 sp<CameraDeviceClient> client = nullptr;
1235 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001236 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 /*out*/client);
1238
1239 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001240 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001241 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001243 }
1244
Ruben Brunkcc776712015-02-17 20:18:47 -08001245 device = client;
1246 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001247}
1248
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001249status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1250 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001251
1252 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001253 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001254 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001255 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001256 }
1257
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001258 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001259 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001260
1261 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001262 auto state = getCameraState(id);
1263 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001264 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001265 return -EINVAL;
1266 }
1267
1268 ICameraServiceListener::Status cameraStatus = state->getStatus();
1269 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1270 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001271 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001272 return -EINVAL;
1273 }
1274
1275 {
1276 Mutex::Autolock al(mTorchStatusMutex);
1277 ICameraServiceListener::TorchStatus status;
1278 status_t res = getTorchStatusLocked(id, &status);
1279 if (res) {
1280 ALOGE("%s: getting current torch status failed for camera %s",
1281 __FUNCTION__, id.string());
1282 return -EINVAL;
1283 }
1284
1285 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001287 ALOGE("%s: torch mode of camera %s is not available because "
1288 "camera is in use", __FUNCTION__, id.string());
1289 return -EBUSY;
1290 } else {
1291 ALOGE("%s: torch mode of camera %s is not available due to "
1292 "insufficient resources", __FUNCTION__, id.string());
1293 return -EUSERS;
1294 }
1295 }
1296 }
1297
Ruben Brunk99e69712015-05-26 17:25:07 -07001298 {
1299 // Update UID map - this is used in the torch status changed callbacks, so must be done
1300 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001301 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001302 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1303 mTorchUidMap[id].first = uid;
1304 mTorchUidMap[id].second = uid;
1305 } else {
1306 // Set the pending UID
1307 mTorchUidMap[id].first = uid;
1308 }
1309 }
1310
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001311 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001312
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001313 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001314 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1315 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001316 return res;
1317 }
1318
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001319 {
1320 // update the link to client's death
1321 Mutex::Autolock al(mTorchClientMapMutex);
1322 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001323 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001324 if (enabled) {
1325 if (index == NAME_NOT_FOUND) {
1326 mTorchClientMap.add(id, clientBinder);
1327 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001328 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001329 mTorchClientMap.replaceValueAt(index, clientBinder);
1330 }
1331 clientBinder->linkToDeath(this);
1332 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001333 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001334 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001335 }
1336
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001337 return OK;
1338}
1339
Ruben Brunk6267b532015-04-30 17:44:07 -07001340void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001341 ATRACE_CALL();
1342
Ruben Brunk36597b22015-03-20 22:15:57 -07001343 switch(eventId) {
1344 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001345 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001346 break;
1347 }
1348 case ICameraService::NO_EVENT:
1349 default: {
1350 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1351 eventId);
1352 break;
1353 }
1354 }
1355}
1356
Ruben Brunk99e69712015-05-26 17:25:07 -07001357status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001358 ATRACE_CALL();
1359
Igor Murashkinbfc99152013-02-27 12:55:20 -08001360 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001361
Ruben Brunk3450ba72015-06-16 11:00:37 -07001362 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001363 ALOGE("%s: Listener must not be null", __FUNCTION__);
1364 return BAD_VALUE;
1365 }
1366
Igor Murashkinbfc99152013-02-27 12:55:20 -08001367 Mutex::Autolock lock(mServiceLock);
1368
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 {
1370 Mutex::Autolock lock(mStatusListenerLock);
1371 for (auto& it : mListenerList) {
1372 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1373 ALOGW("%s: Tried to add listener %p which was already subscribed",
1374 __FUNCTION__, listener.get());
1375 return ALREADY_EXISTS;
1376 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001377 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001378
1379 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001380 }
1381
Igor Murashkinbfc99152013-02-27 12:55:20 -08001382
Igor Murashkincba2c162013-03-20 15:56:31 -07001383 /* Immediately signal current status to this listener only */
1384 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 Mutex::Autolock lock(mCameraStatesLock);
1386 for (auto& i : mCameraStates) {
1387 // TODO: Update binder to use String16 for camera IDs and remove;
1388 int id = cameraIdToInt(i.first);
1389 if (id == -1) continue;
1390
1391 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001392 }
1393 }
1394
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001395 /* Immediately signal current torch status to this listener only */
1396 {
1397 Mutex::Autolock al(mTorchStatusMutex);
1398 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001399 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1400 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001401 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001402 }
1403
Igor Murashkinbfc99152013-02-27 12:55:20 -08001404 return OK;
1405}
Ruben Brunkcc776712015-02-17 20:18:47 -08001406
1407status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001408 ATRACE_CALL();
1409
Igor Murashkinbfc99152013-02-27 12:55:20 -08001410 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1411
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001412 if (listener == 0) {
1413 ALOGE("%s: Listener must not be null", __FUNCTION__);
1414 return BAD_VALUE;
1415 }
1416
Igor Murashkinbfc99152013-02-27 12:55:20 -08001417 Mutex::Autolock lock(mServiceLock);
1418
Ruben Brunkcc776712015-02-17 20:18:47 -08001419 {
1420 Mutex::Autolock lock(mStatusListenerLock);
1421 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1422 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1423 mListenerList.erase(it);
1424 return OK;
1425 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001426 }
1427 }
1428
1429 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1430 __FUNCTION__, listener.get());
1431
1432 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001433}
1434
Ruben Brunkcc776712015-02-17 20:18:47 -08001435status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001436
1437 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001438 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1439
1440 if (parameters == NULL) {
1441 ALOGE("%s: parameters must not be null", __FUNCTION__);
1442 return BAD_VALUE;
1443 }
1444
1445 status_t ret = 0;
1446
1447 CameraParameters shimParams;
1448 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1449 // Error logged by caller
1450 return ret;
1451 }
1452
1453 String8 shimParamsString8 = shimParams.flatten();
1454 String16 shimParamsString16 = String16(shimParamsString8);
1455
1456 *parameters = shimParamsString16;
1457
1458 return OK;
1459}
1460
1461status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001462 ATRACE_CALL();
1463
Igor Murashkin65d14b92014-06-17 12:03:20 -07001464 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1465
1466 switch (apiVersion) {
1467 case API_VERSION_1:
1468 case API_VERSION_2:
1469 break;
1470 default:
1471 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1472 return BAD_VALUE;
1473 }
1474
1475 int facing = -1;
1476 int deviceVersion = getDeviceVersion(cameraId, &facing);
1477
1478 switch(deviceVersion) {
1479 case CAMERA_DEVICE_API_VERSION_1_0:
1480 case CAMERA_DEVICE_API_VERSION_2_0:
1481 case CAMERA_DEVICE_API_VERSION_2_1:
1482 case CAMERA_DEVICE_API_VERSION_3_0:
1483 case CAMERA_DEVICE_API_VERSION_3_1:
1484 if (apiVersion == API_VERSION_2) {
1485 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1486 __FUNCTION__, cameraId);
1487 return -EOPNOTSUPP;
1488 } else { // if (apiVersion == API_VERSION_1) {
1489 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1490 __FUNCTION__, cameraId);
1491 return OK;
1492 }
1493 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001494 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001495 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1496 __FUNCTION__, cameraId);
1497 return OK;
1498 case -1:
1499 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1500 return BAD_VALUE;
1501 default:
1502 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1503 return INVALID_OPERATION;
1504 }
1505
1506 return OK;
1507}
1508
Ruben Brunkcc776712015-02-17 20:18:47 -08001509void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001510 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001511 for (auto& i : mActiveClientManager.getAll()) {
1512 auto clientSp = i->getValue();
1513 if (clientSp.get() == client) {
1514 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001515 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001516 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001517}
1518
Ruben Brunkcc776712015-02-17 20:18:47 -08001519bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1520 const int callingPid = getCallingPid();
1521 const int servicePid = getpid();
1522 bool ret = false;
1523 {
1524 // Acquire mServiceLock and prevent other clients from connecting
1525 std::unique_ptr<AutoConditionLock> lock =
1526 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001527
Igor Murashkin634a5152013-02-20 17:15:11 -08001528
Ruben Brunkcc776712015-02-17 20:18:47 -08001529 std::vector<sp<BasicClient>> evicted;
1530 for (auto& i : mActiveClientManager.getAll()) {
1531 auto clientSp = i->getValue();
1532 if (clientSp.get() == nullptr) {
1533 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1534 mActiveClientManager.remove(i);
1535 continue;
1536 }
1537 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1538 callingPid == clientSp->getClientPid())) {
1539 mActiveClientManager.remove(i);
1540 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001541
Ruben Brunkcc776712015-02-17 20:18:47 -08001542 // Notify the client of disconnection
1543 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1544 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001545 }
1546 }
1547
Ruben Brunkcc776712015-02-17 20:18:47 -08001548 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1549 // other clients from connecting in mServiceLockWrapper if held
1550 mServiceLock.unlock();
1551
Ruben Brunk36597b22015-03-20 22:15:57 -07001552 // Do not clear caller identity, remote caller should be client proccess
1553
Ruben Brunkcc776712015-02-17 20:18:47 -08001554 for (auto& i : evicted) {
1555 if (i.get() != nullptr) {
1556 i->disconnect();
1557 ret = true;
1558 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001559 }
1560
Ruben Brunkcc776712015-02-17 20:18:47 -08001561 // Reacquire mServiceLock
1562 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001563
Ruben Brunkcc776712015-02-17 20:18:47 -08001564 } // lock is destroyed, allow further connect calls
1565
1566 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001567}
1568
Igor Murashkinecf17e82012-10-02 16:05:11 -07001569
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001570/**
1571 * Check camera capabilities, such as support for basic color operation
1572 */
1573int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1574
1575 // Assume all devices pre-v3.3 are backward-compatible
1576 bool isBackwardCompatible = true;
1577 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1578 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1579 isBackwardCompatible = false;
1580 status_t res;
1581 camera_metadata_ro_entry_t caps;
1582 res = find_camera_metadata_ro_entry(
1583 info.static_camera_characteristics,
1584 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1585 &caps);
1586 if (res != 0) {
1587 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1588 __FUNCTION__, id);
1589 caps.count = 0;
1590 }
1591 for (size_t i = 0; i < caps.count; i++) {
1592 if (caps.data.u8[i] ==
1593 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1594 isBackwardCompatible = true;
1595 break;
1596 }
1597 }
1598 }
1599
1600 if (!isBackwardCompatible) {
1601 mNumberOfNormalCameras--;
1602 *latestStrangeCameraId = id;
1603 } else {
1604 if (id > *latestStrangeCameraId) {
1605 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1606 "This is not allowed due backward-compatibility requirements",
1607 __FUNCTION__, id, *latestStrangeCameraId);
1608 logServiceError("Invalid order of camera devices", ENODEV);
1609 mNumberOfCameras = 0;
1610 mNumberOfNormalCameras = 0;
1611 return INVALID_OPERATION;
1612 }
1613 }
1614 return OK;
1615}
1616
Ruben Brunkcc776712015-02-17 20:18:47 -08001617std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1618 const String8& cameraId) const {
1619 std::shared_ptr<CameraState> state;
1620 {
1621 Mutex::Autolock lock(mCameraStatesLock);
1622 auto iter = mCameraStates.find(cameraId);
1623 if (iter != mCameraStates.end()) {
1624 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 }
1626 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001627 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628}
1629
Ruben Brunkcc776712015-02-17 20:18:47 -08001630sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1631 // Remove from active clients list
1632 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1633 if (clientDescriptorPtr == nullptr) {
1634 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1635 cameraId.string());
1636 return sp<BasicClient>{nullptr};
1637 }
1638
1639 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001640}
1641
Ruben Brunk6267b532015-04-30 17:44:07 -07001642void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001643 // Acquire mServiceLock and prevent other clients from connecting
1644 std::unique_ptr<AutoConditionLock> lock =
1645 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1646
Ruben Brunk6267b532015-04-30 17:44:07 -07001647 std::set<userid_t> newAllowedUsers;
1648 for (size_t i = 0; i < length; i++) {
1649 if (newUserId[i] < 0) {
1650 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1651 __FUNCTION__, newUserId[i]);
1652 return;
1653 }
1654 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001655 }
1656
Ruben Brunka8ca9152015-04-07 14:23:40 -07001657
Ruben Brunk6267b532015-04-30 17:44:07 -07001658 if (newAllowedUsers == mAllowedUsers) {
1659 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1660 return;
1661 }
1662
1663 logUserSwitch(mAllowedUsers, newAllowedUsers);
1664
1665 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001666
1667 // Current user has switched, evict all current clients.
1668 std::vector<sp<BasicClient>> evicted;
1669 for (auto& i : mActiveClientManager.getAll()) {
1670 auto clientSp = i->getValue();
1671
1672 if (clientSp.get() == nullptr) {
1673 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1674 continue;
1675 }
1676
Ruben Brunk6267b532015-04-30 17:44:07 -07001677 // Don't evict clients that are still allowed.
1678 uid_t clientUid = clientSp->getClientUid();
1679 userid_t clientUserId = multiuser_get_user_id(clientUid);
1680 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1681 continue;
1682 }
1683
Ruben Brunk36597b22015-03-20 22:15:57 -07001684 evicted.push_back(clientSp);
1685
1686 String8 curTime = getFormattedCurrentTime();
1687
1688 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1689 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001690
Ruben Brunk36597b22015-03-20 22:15:57 -07001691 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001692 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001693 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001694 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1695 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001696
1697 }
1698
1699 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1700 // blocking other clients from connecting in mServiceLockWrapper if held.
1701 mServiceLock.unlock();
1702
1703 // Clear caller identity temporarily so client disconnect PID checks work correctly
1704 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1705
1706 for (auto& i : evicted) {
1707 i->disconnect();
1708 }
1709
1710 IPCThreadState::self()->restoreCallingIdentity(token);
1711
1712 // Reacquire mServiceLock
1713 mServiceLock.lock();
1714}
Ruben Brunkcc776712015-02-17 20:18:47 -08001715
Ruben Brunka8ca9152015-04-07 14:23:40 -07001716void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001717 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001718 Mutex::Autolock l(mLogLock);
1719 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720}
1721
Ruben Brunka8ca9152015-04-07 14:23:40 -07001722void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001723 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001724 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001725 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001726 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001727}
1728
1729void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001730 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001731 // Log the clients evicted
1732 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001733 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001734}
1735
1736void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001737 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001738 // Log the client rejected
1739 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001740 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001741}
1742
Ruben Brunk6267b532015-04-30 17:44:07 -07001743void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1744 const std::set<userid_t>& newUserIds) {
1745 String8 newUsers = toString(newUserIds);
1746 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001747 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001748 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1749 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001750}
1751
1752void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1753 // Log the device removal
1754 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1755}
1756
1757void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1758 // Log the device removal
1759 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1760}
1761
1762void CameraService::logClientDied(int clientPid, const char* reason) {
1763 // Log the device removal
1764 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001765}
1766
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001767void CameraService::logServiceError(const char* msg, int errorCode) {
1768 String8 curTime = getFormattedCurrentTime();
1769 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1770}
1771
Ruben Brunk36597b22015-03-20 22:15:57 -07001772status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1773 uint32_t flags) {
1774
1775 const int pid = getCallingPid();
1776 const int selfPid = getpid();
1777
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778 // Permission checks
1779 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001780 case BnCameraService::CONNECT:
1781 case BnCameraService::CONNECT_DEVICE:
1782 case BnCameraService::CONNECT_LEGACY: {
1783 if (pid != selfPid) {
1784 // we're called from a different process, do the real check
1785 if (!checkCallingPermission(
1786 String16("android.permission.CAMERA"))) {
1787 const int uid = getCallingUid();
1788 ALOGE("Permission Denial: "
1789 "can't use the camera pid=%d, uid=%d", pid, uid);
1790 return PERMISSION_DENIED;
1791 }
1792 }
1793 break;
1794 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001795 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1796 if (pid != selfPid) {
1797 // Ensure we're being called by system_server, or similar process with
1798 // permissions to notify the camera service about system events
1799 if (!checkCallingPermission(
1800 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1801 const int uid = getCallingUid();
1802 ALOGE("Permission Denial: cannot send updates to camera service about system"
1803 " events from pid=%d, uid=%d", pid, uid);
1804 return PERMISSION_DENIED;
1805 }
1806 }
1807 break;
1808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809 }
1810
1811 return BnCameraService::onTransact(code, data, reply, flags);
1812}
1813
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814// We share the media players for shutter and recording sound for all clients.
1815// A reference count is kept to determine when we will actually release the
1816// media players.
1817
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001818MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001820 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001821 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 mp->prepare();
1823 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001824 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 return NULL;
1826 }
1827 return mp;
1828}
1829
1830void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001831 ATRACE_CALL();
1832
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 Mutex::Autolock lock(mSoundLock);
1834 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1835 if (mSoundRef++) return;
1836
1837 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001838 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1839 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840}
1841
1842void CameraService::releaseSound() {
1843 Mutex::Autolock lock(mSoundLock);
1844 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1845 if (--mSoundRef) return;
1846
1847 for (int i = 0; i < NUM_SOUNDS; i++) {
1848 if (mSoundPlayer[i] != 0) {
1849 mSoundPlayer[i]->disconnect();
1850 mSoundPlayer[i].clear();
1851 }
1852 }
1853}
1854
1855void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001856 ATRACE_CALL();
1857
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 LOG1("playSound(%d)", kind);
1859 Mutex::Autolock lock(mSoundLock);
1860 sp<MediaPlayer> player = mSoundPlayer[kind];
1861 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001862 player->seekTo(0);
1863 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 }
1865}
1866
1867// ----------------------------------------------------------------------------
1868
1869CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001870 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001871 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001872 int cameraId, int cameraFacing,
1873 int clientPid, uid_t clientUid,
1874 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001875 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001876 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001877 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001878 cameraId, cameraFacing,
1879 clientPid, clientUid,
1880 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001881{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001883 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001885 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001888
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001889 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890}
1891
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892// tear down the client
1893CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001894 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001895 mDestructionStarted = true;
1896
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001897 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001898 // unconditionally disconnect. function is idempotent
1899 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900}
1901
Igor Murashkin634a5152013-02-20 17:15:11 -08001902CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001903 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001904 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001905 int cameraId, int cameraFacing,
1906 int clientPid, uid_t clientUid,
1907 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001908 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001909{
1910 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001911 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001912 mCameraId = cameraId;
1913 mCameraFacing = cameraFacing;
1914 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001915 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001916 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001917 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001918 mDestructionStarted = false;
1919}
1920
1921CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001922 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001923 mDestructionStarted = true;
1924}
1925
1926void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001927 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001928 return;
1929 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001930 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001931
1932 mCameraService->removeByClient(this);
1933 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001934 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001935
1936 sp<IBinder> remote = getRemote();
1937 if (remote != nullptr) {
1938 remote->unlinkToDeath(mCameraService);
1939 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001940
1941 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001942 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1943
Igor Murashkincba2c162013-03-20 15:56:31 -07001944 // client shouldn't be able to call into us anymore
1945 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001946}
1947
Ruben Brunkcc776712015-02-17 20:18:47 -08001948String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001949 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001950}
1951
1952
1953int CameraService::BasicClient::getClientPid() const {
1954 return mClientPid;
1955}
1956
Ruben Brunk6267b532015-04-30 17:44:07 -07001957uid_t CameraService::BasicClient::getClientUid() const {
1958 return mClientUid;
1959}
1960
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001961bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1962 // Defaults to API2.
1963 return level == API_2;
1964}
1965
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001966status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001967 ATRACE_CALL();
1968
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001969 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001970 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001971 mOpsCallback = new OpsCallback(this);
1972
Igor Murashkine6800ce2013-03-04 17:25:57 -08001973 {
1974 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001975 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001976 }
1977
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001978 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001979 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001980 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001981 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001982
Svetoslav28e8ef72015-05-11 19:21:31 -07001983 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001984 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001985 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001986 return PERMISSION_DENIED;
1987 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001988
Svetoslav28e8ef72015-05-11 19:21:31 -07001989 if (res == AppOpsManager::MODE_IGNORED) {
1990 ALOGI("Camera %d: Access for \"%s\" has been restricted",
1991 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07001992 // Return the same error as for device policy manager rejection
1993 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07001994 }
1995
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001996 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001997
1998 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1999 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002000 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002001
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002002 // Transition device state to OPEN
2003 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2004 String8::format("%d", mCameraId));
2005
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002006 return OK;
2007}
2008
2009status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002010 ATRACE_CALL();
2011
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002012 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002013 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002014 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002015 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002016 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002017 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002018
Ruben Brunkcc776712015-02-17 20:18:47 -08002019 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2020 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002021
Ruben Brunkcc776712015-02-17 20:18:47 -08002022 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002023 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002025
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002026 // Transition device state to CLOSED
2027 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2028 String8::format("%d", mCameraId));
2029
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002030 // Notify flashlight that a camera device is closed.
2031 mCameraService->mFlashlight->deviceClosed(
2032 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002033 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002034 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002035 if (mOpsCallback != NULL) {
2036 mAppOpsManager.stopWatchingMode(mOpsCallback);
2037 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002038 mOpsCallback.clear();
2039
2040 return OK;
2041}
2042
2043void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002044 ATRACE_CALL();
2045
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002046 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002047 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002048
2049 if (op != AppOpsManager::OP_CAMERA) {
2050 ALOGW("Unexpected app ops notification received: %d", op);
2051 return;
2052 }
2053
2054 int32_t res;
2055 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002056 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002057 ALOGV("checkOp returns: %d, %s ", res,
2058 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2059 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2060 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2061 "UNKNOWN");
2062
2063 if (res != AppOpsManager::MODE_ALLOWED) {
2064 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2065 myName.string());
2066 // Reset the client PID to allow server-initiated disconnect,
2067 // and to prevent further calls by client.
2068 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002069 CaptureResultExtras resultExtras; // a dummy result (invalid)
2070 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002071 disconnect();
2072 }
2073}
2074
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075// ----------------------------------------------------------------------------
2076
Ruben Brunkcc776712015-02-17 20:18:47 -08002077// Provide client strong pointer for callbacks.
2078sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2079 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2080 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2081 if (clientDescriptor != nullptr) {
2082 return sp<Client>{
2083 static_cast<Client*>(clientDescriptor->getValue().get())};
2084 }
2085 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086}
2087
Jianing Weicb0652e2014-03-12 18:29:36 -07002088void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2089 const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002090 if (mRemoteCallback != NULL) {
2091 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2092 } else {
2093 ALOGE("mRemoteCallback is NULL!!");
2094 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002095}
2096
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002097// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002098void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002099 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002100 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002101}
2102
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002103bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2104 return level == API_1;
2105}
2106
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002107CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2108 mClient(client) {
2109}
2110
2111void CameraService::Client::OpsCallback::opChanged(int32_t op,
2112 const String16& packageName) {
2113 sp<BasicClient> client = mClient.promote();
2114 if (client != NULL) {
2115 client->opChanged(op, packageName);
2116 }
2117}
2118
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002120// CameraState
2121// ----------------------------------------------------------------------------
2122
2123CameraService::CameraState::CameraState(const String8& id, int cost,
2124 const std::set<String8>& conflicting) : mId(id),
2125 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2126
2127CameraService::CameraState::~CameraState() {}
2128
2129ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2130 Mutex::Autolock lock(mStatusLock);
2131 return mStatus;
2132}
2133
2134CameraParameters CameraService::CameraState::getShimParams() const {
2135 return mShimParams;
2136}
2137
2138void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2139 mShimParams = params;
2140}
2141
2142int CameraService::CameraState::getCost() const {
2143 return mCost;
2144}
2145
2146std::set<String8> CameraService::CameraState::getConflicting() const {
2147 return mConflicting;
2148}
2149
2150String8 CameraService::CameraState::getId() const {
2151 return mId;
2152}
2153
2154// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002155// ClientEventListener
2156// ----------------------------------------------------------------------------
2157
2158void CameraService::ClientEventListener::onClientAdded(
2159 const resource_policy::ClientDescriptor<String8,
2160 sp<CameraService::BasicClient>>& descriptor) {
2161 auto basicClient = descriptor.getValue();
2162 if (basicClient.get() != nullptr) {
2163 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2164 notifier.noteStartCamera(descriptor.getKey(),
2165 static_cast<int>(basicClient->getClientUid()));
2166 }
2167}
2168
2169void CameraService::ClientEventListener::onClientRemoved(
2170 const resource_policy::ClientDescriptor<String8,
2171 sp<CameraService::BasicClient>>& descriptor) {
2172 auto basicClient = descriptor.getValue();
2173 if (basicClient.get() != nullptr) {
2174 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2175 notifier.noteStopCamera(descriptor.getKey(),
2176 static_cast<int>(basicClient->getClientUid()));
2177 }
2178}
2179
2180
2181// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002182// CameraClientManager
2183// ----------------------------------------------------------------------------
2184
Ruben Brunk99e69712015-05-26 17:25:07 -07002185CameraService::CameraClientManager::CameraClientManager() {
2186 setListener(std::make_shared<ClientEventListener>());
2187}
2188
Ruben Brunkcc776712015-02-17 20:18:47 -08002189CameraService::CameraClientManager::~CameraClientManager() {}
2190
2191sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2192 const String8& id) const {
2193 auto descriptor = get(id);
2194 if (descriptor == nullptr) {
2195 return sp<BasicClient>{nullptr};
2196 }
2197 return descriptor->getValue();
2198}
2199
2200String8 CameraService::CameraClientManager::toString() const {
2201 auto all = getAll();
2202 String8 ret("[");
2203 bool hasAny = false;
2204 for (auto& i : all) {
2205 hasAny = true;
2206 String8 key = i->getKey();
2207 int32_t cost = i->getCost();
2208 int32_t pid = i->getOwnerId();
2209 int32_t priority = i->getPriority();
2210 auto conflicting = i->getConflicting();
2211 auto clientSp = i->getValue();
2212 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002213 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002214 if (clientSp.get() != nullptr) {
2215 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002216 uid_t clientUid = clientSp->getClientUid();
2217 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002218 }
2219 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2220 PRId32 ", ", key.string(), cost, pid, priority);
2221
Ruben Brunk6267b532015-04-30 17:44:07 -07002222 if (clientSp.get() != nullptr) {
2223 ret.appendFormat("User Id: %d, ", clientUserId);
2224 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002225 if (packageName.size() != 0) {
2226 ret.appendFormat("Client Package Name: %s", packageName.string());
2227 }
2228
2229 ret.append(", Conflicting Client Devices: {");
2230 for (auto& j : conflicting) {
2231 ret.appendFormat("%s, ", j.string());
2232 }
2233 ret.append("})");
2234 }
2235 if (hasAny) ret.append("\n");
2236 ret.append("]\n");
2237 return ret;
2238}
2239
2240CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2241 const String8& key, const sp<BasicClient>& value, int32_t cost,
2242 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2243
2244 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2245 key, value, cost, conflictingKeys, priority, ownerId);
2246}
2247
2248CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2249 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2250 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2251 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2252}
2253
2254// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255
2256static const int kDumpLockRetries = 50;
2257static const int kDumpLockSleep = 60000;
2258
2259static bool tryLock(Mutex& mutex)
2260{
2261 bool locked = false;
2262 for (int i = 0; i < kDumpLockRetries; ++i) {
2263 if (mutex.tryLock() == NO_ERROR) {
2264 locked = true;
2265 break;
2266 }
2267 usleep(kDumpLockSleep);
2268 }
2269 return locked;
2270}
2271
2272status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002273 ATRACE_CALL();
2274
Ruben Brunka8ca9152015-04-07 14:23:40 -07002275 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002277 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 "can't dump CameraService from pid=%d, uid=%d\n",
2279 getCallingPid(),
2280 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 write(fd, result.string(), result.size());
2282 } else {
2283 bool locked = tryLock(mServiceLock);
2284 // failed to lock - CameraService is probably deadlocked
2285 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002286 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002287 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 }
2289
2290 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002291 if (!mModule) {
2292 result = String8::format("No camera module available!\n");
2293 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002294
2295 // Dump event log for error information
2296 dumpEventLog(fd);
2297
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002298 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002299 return NO_ERROR;
2300 }
2301
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002302 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2303 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2304 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2305 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002306 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2307 String8 activeClientString = mActiveClientManager.toString();
2308 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002309 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002310
Ruben Brunkf81648e2014-04-17 16:14:57 -07002311 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2312 if (desc == NULL) {
2313 result.appendFormat("Vendor tags left unimplemented.\n");
2314 } else {
2315 result.appendFormat("Vendor tag definitions:\n");
2316 }
2317
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002318 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002319
2320 if (desc != NULL) {
2321 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2322 }
2323
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002324 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002325
2326 bool stateLocked = tryLock(mCameraStatesLock);
2327 if (!stateLocked) {
2328 result = String8::format("CameraStates in use, may be deadlocked\n");
2329 write(fd, result.string(), result.size());
2330 }
2331
2332 for (auto& state : mCameraStates) {
2333 String8 cameraId = state.first;
2334 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002335 camera_info info;
2336
Ruben Brunkcc776712015-02-17 20:18:47 -08002337 // TODO: Change getCameraInfo + HAL to use String cameraIds
2338 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002339 if (rc != OK) {
2340 result.appendFormat(" Error reading static information!\n");
2341 write(fd, result.string(), result.size());
2342 } else {
2343 result.appendFormat(" Facing: %s\n",
2344 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2345 result.appendFormat(" Orientation: %d\n", info.orientation);
2346 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002347 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002348 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2349 } else {
2350 deviceVersion = info.device_version;
2351 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002352
2353 auto conflicting = state.second->getConflicting();
2354 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2355 result.appendFormat(" Conflicting Devices:");
2356 for (auto& id : conflicting) {
2357 result.appendFormat(" %s", cameraId.string());
2358 }
2359 if (conflicting.size() == 0) {
2360 result.appendFormat(" NONE");
2361 }
2362 result.appendFormat("\n");
2363
2364 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002365 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2366 result.appendFormat(" Device static metadata:\n");
2367 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002368 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002369 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002370 } else {
2371 write(fd, result.string(), result.size());
2372 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002373
2374 CameraParameters p = state.second->getShimParams();
2375 if (!p.isEmpty()) {
2376 result = String8::format(" Camera1 API shim is using parameters:\n ");
2377 write(fd, result.string(), result.size());
2378 p.dump(fd, args);
2379 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002380 }
2381
Ruben Brunkcc776712015-02-17 20:18:47 -08002382 auto clientDescriptor = mActiveClientManager.get(cameraId);
2383 if (clientDescriptor == nullptr) {
2384 result = String8::format(" Device %s is closed, no client instance\n",
2385 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002386 write(fd, result.string(), result.size());
2387 continue;
2388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002389 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002390 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2391 cameraId.string());
2392 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2393 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2394
2395 auto client = clientDescriptor->getValue();
2396 result.appendFormat("Client package: %s\n",
2397 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002398 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002399
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002400 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002402
2403 if (stateLocked) mCameraStatesLock.unlock();
2404
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002406 result = String8::format("\nNo active camera clients yet.\n");
2407 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 }
2409
2410 if (locked) mServiceLock.unlock();
2411
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002412 // Dump camera traces if there were any
2413 write(fd, "\n", 1);
2414 camera3::CameraTraces::dump(fd, args);
2415
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416 // change logging level
2417 int n = args.size();
2418 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002419 String16 verboseOption("-v");
2420 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 String8 levelStr(args[i+1]);
2422 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002423 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002425 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 }
2427 }
2428 }
2429 return NO_ERROR;
2430}
2431
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002432void CameraService::dumpEventLog(int fd) {
2433 String8 result = String8("\nPrior client events (most recent at top):\n");
2434
2435 Mutex::Autolock l(mLogLock);
2436 for (const auto& msg : mEventLog) {
2437 result.appendFormat(" %s\n", msg.string());
2438 }
2439
2440 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2441 result.append(" ...\n");
2442 } else if (mEventLog.size() == 0) {
2443 result.append(" [no events yet]\n");
2444 }
2445 result.append("\n");
2446
2447 write(fd, result.string(), result.size());
2448}
2449
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002450void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002451 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002452 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2453 if (mTorchClientMap[i] == who) {
2454 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002455 String8 cameraId = mTorchClientMap.keyAt(i);
2456 status_t res = mFlashlight->setTorchMode(cameraId, false);
2457 if (res) {
2458 ALOGE("%s: torch client died but couldn't turn off torch: "
2459 "%s (%d)", __FUNCTION__, strerror(-res), res);
2460 return;
2461 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002462 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002463 break;
2464 }
2465 }
2466}
2467
Ruben Brunkcc776712015-02-17 20:18:47 -08002468/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002469
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002470 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002471 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2472 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002473 */
2474
Ruben Brunka8ca9152015-04-07 14:23:40 -07002475 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2476
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002477 // check torch client
2478 handleTorchClientBinderDied(who);
2479
2480 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002481 if(!evictClientIdByRemote(who)) {
2482 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002483 return;
2484 }
2485
Ruben Brunkcc776712015-02-17 20:18:47 -08002486 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2487 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002488}
2489
Ruben Brunkcc776712015-02-17 20:18:47 -08002490void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2491 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002492}
2493
Ruben Brunkcc776712015-02-17 20:18:47 -08002494void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2495 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2496 // Do not lock mServiceLock here or can get into a deadlock from
2497 // connect() -> disconnect -> updateStatus
2498
2499 auto state = getCameraState(cameraId);
2500
2501 if (state == nullptr) {
2502 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2503 cameraId.string());
2504 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002505 }
2506
Ruben Brunkcc776712015-02-17 20:18:47 -08002507 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2508 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2509 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2510 (const String8& cameraId, ICameraServiceListener::Status status) {
2511
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002512 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2513 // Update torch status if it has a flash unit.
2514 Mutex::Autolock al(mTorchStatusMutex);
2515 ICameraServiceListener::TorchStatus torchStatus;
2516 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2517 NAME_NOT_FOUND) {
2518 ICameraServiceListener::TorchStatus newTorchStatus =
2519 status == ICameraServiceListener::STATUS_PRESENT ?
2520 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2521 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2522 if (torchStatus != newTorchStatus) {
2523 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2524 }
2525 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002526 }
2527
2528 Mutex::Autolock lock(mStatusListenerLock);
2529
2530 for (auto& listener : mListenerList) {
2531 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2532 int id = cameraIdToInt(cameraId);
2533 if (id != -1) listener->onStatusChanged(status, id);
2534 }
2535 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002536}
2537
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002538void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2539 const String8& cameraId) {
2540 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2541 if (proxyBinder == nullptr) return;
2542 String16 id(cameraId);
2543 proxyBinder->notifyCameraState(id, newState);
2544}
2545
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002546status_t CameraService::getTorchStatusLocked(
2547 const String8& cameraId,
2548 ICameraServiceListener::TorchStatus *status) const {
2549 if (!status) {
2550 return BAD_VALUE;
2551 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002552 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2553 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002554 // invalid camera ID or the camera doesn't have a flash unit
2555 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002556 }
2557
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002558 *status = mTorchStatusMap.valueAt(index);
2559 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002560}
2561
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002562status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002563 ICameraServiceListener::TorchStatus status) {
2564 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2565 if (index == NAME_NOT_FOUND) {
2566 return BAD_VALUE;
2567 }
2568 ICameraServiceListener::TorchStatus& item =
2569 mTorchStatusMap.editValueAt(index);
2570 item = status;
2571
2572 return OK;
2573}
2574
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575}; // namespace android