blob: f42fada2ee955456e41902385c3cc7ad894611ee [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"
Iliyan Malchev8951a972011-04-14 16:55:59 -070018//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070019
Ruben Brunkcc776712015-02-17 20:18:47 -080020#include <algorithm>
21#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070022#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080023#include <cstring>
24#include <ctime>
25#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070026#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080027#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <pthread.h>
29
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080030#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
33#include <binder/MemoryBase.h>
34#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080035#include <binder/ProcessInfoService.h>
Ruben Brunk2823ce02015-05-19 17:25:13 -070036#include <camera/ICameraServiceProxy.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070038#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080039#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <hardware/hardware.h>
41#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080042#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070044#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/Errors.h>
46#include <utils/Log.h>
47#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080048#include <utils/Trace.h>
49#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070050#include <system/camera_metadata.h>
51#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070054#include "api1/CameraClient.h"
55#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070057#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070058#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
60namespace android {
61
62// ----------------------------------------------------------------------------
63// Logging support -- this is for debugging only
64// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070065volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Steve Blockb8a80522011-12-20 16:23:08 +000067#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
70static void setLogLevel(int level) {
71 android_atomic_write(level, &gLogLevel);
72}
73
74// ----------------------------------------------------------------------------
75
Igor Murashkincba2c162013-03-20 15:56:31 -070076extern "C" {
77static void camera_device_status_change(
78 const struct camera_module_callbacks* callbacks,
79 int camera_id,
80 int new_status) {
81 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080082 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070083
Ruben Brunkcc776712015-02-17 20:18:47 -080084 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
85 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070086}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080087
88static void torch_mode_status_change(
89 const struct camera_module_callbacks* callbacks,
90 const char* camera_id,
91 int new_status) {
92 if (!callbacks || !camera_id) {
93 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
94 callbacks, camera_id);
95 }
96 sp<CameraService> cs = const_cast<CameraService*>(
97 static_cast<const CameraService*>(callbacks));
98
99 ICameraServiceListener::TorchStatus status;
100 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800101 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800102 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
103 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800104 case TORCH_MODE_STATUS_AVAILABLE_OFF:
105 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
106 break;
107 case TORCH_MODE_STATUS_AVAILABLE_ON:
108 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800109 break;
110 default:
111 ALOGE("Unknown torch status %d", new_status);
112 return;
113 }
114
115 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800116 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800117 status);
118}
Igor Murashkincba2c162013-03-20 15:56:31 -0700119} // extern "C"
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
123// This is ugly and only safe if we never re-create the CameraService, but
124// should be ok for now.
125static CameraService *gCameraService;
126
Ruben Brunk6267b532015-04-30 17:44:07 -0700127CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH), mAllowedUsers(),
128 mSoundRef(0), mModule(0), mFlashlight(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000129 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800131
Igor Murashkincba2c162013-03-20 15:56:31 -0700132 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800133 this->torch_mode_status_change = android::torch_mode_status_change;
134
Ruben Brunkcc776712015-02-17 20:18:47 -0800135 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136}
137
Iliyan Malchev8951a972011-04-14 16:55:59 -0700138void CameraService::onFirstRef()
139{
Ruben Brunkcc776712015-02-17 20:18:47 -0800140 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800141
Iliyan Malchev8951a972011-04-14 16:55:59 -0700142 BnCameraService::onFirstRef();
143
Ruben Brunk99e69712015-05-26 17:25:07 -0700144 // Update battery life tracking if service is restarting
145 BatteryNotifier& notifier(BatteryNotifier::getInstance());
146 notifier.noteResetCamera();
147 notifier.noteResetFlashlight();
148
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800149 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700150 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
151 (const hw_module_t **)&rawModule);
152 if (err < 0) {
153 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
154 logServiceError("Could not load camera HAL module", err);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700155 mNumberOfCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700156 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700157 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800158
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700159 mModule = new CameraModule(rawModule);
160 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
161 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 Talvala1527f072015-04-07 15:55:31 -0700172
173 mNumberOfCameras = mModule->getNumberOfCameras();
174
175 mFlashlight = new CameraFlashlight(*mModule, *this);
176 status_t res = mFlashlight->findFlashUnits();
177 if (res) {
178 // impossible because we haven't open any camera devices.
179 ALOGE("Failed to find flash units.");
180 }
181
182 for (int i = 0; i < mNumberOfCameras; i++) {
183 String8 cameraId = String8::format("%d", i);
184
185 // Defaults to use for cost and conflicting devices
186 int cost = 100;
187 char** conflicting_devices = nullptr;
188 size_t conflicting_devices_length = 0;
189
190 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
191 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4) {
192 struct camera_info info;
193 status_t rc = mModule->getCameraInfo(i, &info);
194 if (rc == NO_ERROR) {
195 cost = info.resource_cost;
196 conflicting_devices = info.conflicting_devices;
197 conflicting_devices_length = info.conflicting_devices_length;
198 } else {
199 ALOGE("%s: Received error loading camera info for device %d, cost and"
200 " conflicting devices fields set to defaults for this device.",
201 __FUNCTION__, i);
202 }
203 }
204
205 std::set<String8> conflicting;
206 for (size_t i = 0; i < conflicting_devices_length; i++) {
207 conflicting.emplace(String8(conflicting_devices[i]));
208 }
209
210 // Initialize state for each camera device
211 {
212 Mutex::Autolock lock(mCameraStatesLock);
213 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
214 conflicting));
215 }
216
217 if (mFlashlight->hasFlashUnit(cameraId)) {
218 mTorchStatusMap.add(cameraId,
219 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
220 }
221 }
222
223 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
224 mModule->setCallbacks(this);
225 }
226
227 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
228
229 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
230 setUpVendorTags();
231 }
232
233 CameraDeviceFactory::registerService(this);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700234
235 CameraService::pingCameraServiceProxy();
236}
237
238void CameraService::pingCameraServiceProxy() {
239 sp<IServiceManager> sm = defaultServiceManager();
240 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
241 if (binder == nullptr) {
242 return;
243 }
244 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
245 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700246}
247
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800249 if (mModule) {
250 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800251 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800252 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800253 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800254 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255}
256
Ruben Brunkcc776712015-02-17 20:18:47 -0800257void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
258 camera_device_status_t newStatus) {
259 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700260 cameraId, newStatus);
261
Ruben Brunkcc776712015-02-17 20:18:47 -0800262 String8 id = String8::format("%d", cameraId);
263 std::shared_ptr<CameraState> state = getCameraState(id);
264
265 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700266 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
267 return;
268 }
269
Ruben Brunkcc776712015-02-17 20:18:47 -0800270 ICameraServiceListener::Status oldStatus = state->getStatus();
271
272 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
273 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700274 return;
275 }
276
Igor Murashkincba2c162013-03-20 15:56:31 -0700277 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700278 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
279 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800280 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700281 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800282 // Don't do this in updateStatus to avoid deadlock over mServiceLock
283 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700284
Ruben Brunkcc776712015-02-17 20:18:47 -0800285 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
286 // to this device until the status changes
287 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700288
Ruben Brunkcc776712015-02-17 20:18:47 -0800289 // Remove cached shim parameters
290 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700291
Ruben Brunkcc776712015-02-17 20:18:47 -0800292 // Remove the client from the list of active clients
293 clientToDisconnect = removeClientLocked(id);
294
295 // Notify the client of disconnection
296 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
297 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700298 }
299
Ruben Brunkcc776712015-02-17 20:18:47 -0800300 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
301 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700302
Ruben Brunkcc776712015-02-17 20:18:47 -0800303 // Disconnect client
304 if (clientToDisconnect.get() != nullptr) {
305 // Ensure not in binder RPC so client disconnect PID checks work correctly
306 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
307 "onDeviceStatusChanged must be called from the camera service process!");
308 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700309 }
310
Ruben Brunkcc776712015-02-17 20:18:47 -0800311 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700312 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
313 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
314 newStatus));
315 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800316 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700317 }
318
Igor Murashkincba2c162013-03-20 15:56:31 -0700319}
320
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800321void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800322 ICameraServiceListener::TorchStatus newStatus) {
323 Mutex::Autolock al(mTorchStatusMutex);
324 onTorchStatusChangedLocked(cameraId, newStatus);
325}
326
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800327void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800328 ICameraServiceListener::TorchStatus newStatus) {
329 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
330 __FUNCTION__, cameraId.string(), newStatus);
331
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800332 ICameraServiceListener::TorchStatus status;
333 status_t res = getTorchStatusLocked(cameraId, &status);
334 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700335 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
336 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800337 return;
338 }
339 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800340 return;
341 }
342
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800343 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800344 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700345 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800346 return;
347 }
348
Ruben Brunkcc776712015-02-17 20:18:47 -0800349 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700350 // Update battery life logging for flashlight
351 Mutex::Autolock al(mTorchClientMapMutex);
352 auto iter = mTorchUidMap.find(cameraId);
353 if (iter != mTorchUidMap.end()) {
354 int oldUid = iter->second.second;
355 int newUid = iter->second.first;
356 BatteryNotifier& notifier(BatteryNotifier::getInstance());
357 if (oldUid != newUid) {
358 // If the UID has changed, log the status and update current UID in mTorchUidMap
359 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
360 notifier.noteFlashlightOff(cameraId, oldUid);
361 }
362 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
363 notifier.noteFlashlightOn(cameraId, newUid);
364 }
365 iter->second.second = newUid;
366 } else {
367 // If the UID has not changed, log the status
368 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
369 notifier.noteFlashlightOn(cameraId, oldUid);
370 } else {
371 notifier.noteFlashlightOff(cameraId, oldUid);
372 }
373 }
374 }
375 }
376
377 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800378 Mutex::Autolock lock(mStatusListenerLock);
379 for (auto& i : mListenerList) {
380 i->onTorchStatusChanged(newStatus, String16{cameraId});
381 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800382 }
383}
384
385
Mathias Agopian65ab4712010-07-14 17:59:35 -0700386int32_t CameraService::getNumberOfCameras() {
387 return mNumberOfCameras;
388}
389
390status_t CameraService::getCameraInfo(int cameraId,
391 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700392 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700393 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700394 }
395
Mathias Agopian65ab4712010-07-14 17:59:35 -0700396 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
397 return BAD_VALUE;
398 }
399
Iliyan Malchev8951a972011-04-14 16:55:59 -0700400 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700401 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800402 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700403 cameraInfo->facing = info.facing;
404 cameraInfo->orientation = info.orientation;
405 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406}
407
Ruben Brunkcc776712015-02-17 20:18:47 -0800408int CameraService::cameraIdToInt(const String8& cameraId) {
409 errno = 0;
410 size_t pos = 0;
411 int ret = stoi(std::string{cameraId.string()}, &pos);
412 if (errno != 0 || pos != cameraId.size()) {
413 return -1;
414 }
415 return ret;
416}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700417
418status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
419 status_t ret = OK;
420 struct CameraInfo info;
421 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
422 return ret;
423 }
424
425 CameraMetadata shimInfo;
426 int32_t orientation = static_cast<int32_t>(info.orientation);
427 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
428 return ret;
429 }
430
431 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
432 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
433 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
434 return ret;
435 }
436
Igor Murashkin65d14b92014-06-17 12:03:20 -0700437 CameraParameters shimParams;
438 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
439 // Error logged by callee
440 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700441 }
442
443 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700444 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700445 Vector<int32_t> formats;
446 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700447 {
448 shimParams.getSupportedPreviewSizes(/*out*/sizes);
449 shimParams.getSupportedPreviewFormats(/*out*/formats);
450 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700451 }
452
453 // Always include IMPLEMENTATION_DEFINED
454 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
455
456 const size_t INTS_PER_CONFIG = 4;
457
458 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700459 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
460
461 Vector<int32_t> streamConfigs;
462 streamConfigs.setCapacity(streamConfigSize);
463
Ruben Brunkb2119af2014-05-09 19:57:56 -0700464 for (size_t i = 0; i < formats.size(); ++i) {
465 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700466 streamConfigs.add(formats[i]);
467 streamConfigs.add(sizes[j].width);
468 streamConfigs.add(sizes[j].height);
469 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700470 }
471 }
472
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700473 for (size_t i = 0; i < jpegSizes.size(); ++i) {
474 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
475 streamConfigs.add(jpegSizes[i].width);
476 streamConfigs.add(jpegSizes[i].height);
477 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
478 }
479
Ruben Brunkb2119af2014-05-09 19:57:56 -0700480 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700481 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700482 return ret;
483 }
484
485 int64_t fakeMinFrames[0];
486 // TODO: Fixme, don't fake min frame durations.
487 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
488 fakeMinFrames, 0)) != OK) {
489 return ret;
490 }
491
492 int64_t fakeStalls[0];
493 // TODO: Fixme, don't fake stall durations.
494 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
495 fakeStalls, 0)) != OK) {
496 return ret;
497 }
498
499 *cameraInfo = shimInfo;
500 return OK;
501}
502
Zhijun He2b59be82013-09-25 10:14:30 -0700503status_t CameraService::getCameraCharacteristics(int cameraId,
504 CameraMetadata* cameraInfo) {
505 if (!cameraInfo) {
506 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
507 return BAD_VALUE;
508 }
509
510 if (!mModule) {
511 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
512 return -ENODEV;
513 }
514
Zhijun He2b59be82013-09-25 10:14:30 -0700515 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
516 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
517 return BAD_VALUE;
518 }
519
520 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700521 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800522 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700523 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
524 /**
525 * Backwards compatibility mode for old HALs:
526 * - Convert CameraInfo into static CameraMetadata properties.
527 * - Retrieve cached CameraParameters for this camera. If none exist,
528 * attempt to open CameraClient and retrieve the CameraParameters.
529 * - Convert cached CameraParameters into static CameraMetadata
530 * properties.
531 */
532 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700533
Ruben Brunkb2119af2014-05-09 19:57:56 -0700534 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
535 return ret;
536 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700537
Ruben Brunkb2119af2014-05-09 19:57:56 -0700538 } else {
539 /**
540 * Normal HAL 2.1+ codepath.
541 */
542 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800543 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700544 *cameraInfo = info.static_camera_characteristics;
545 }
Zhijun He2b59be82013-09-25 10:14:30 -0700546
547 return ret;
548}
549
Ruben Brunkcc776712015-02-17 20:18:47 -0800550int CameraService::getCallingPid() {
551 return IPCThreadState::self()->getCallingPid();
552}
553
554int CameraService::getCallingUid() {
555 return IPCThreadState::self()->getCallingUid();
556}
557
558String8 CameraService::getFormattedCurrentTime() {
559 time_t now = time(nullptr);
560 char formattedTime[64];
561 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
562 return String8(formattedTime);
563}
564
565int CameraService::getCameraPriorityFromProcState(int procState) {
566 // Find the priority for the camera usage based on the process state. Higher priority clients
567 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700568 if (procState < 0) {
569 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
570 procState);
571 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800572 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700573 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800574}
575
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800576status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
577 if (!mModule) {
578 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
579 return -ENODEV;
580 }
581
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800582 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
583 return OK;
584}
585
Igor Murashkin634a5152013-02-20 17:15:11 -0800586int CameraService::getDeviceVersion(int cameraId, int* facing) {
587 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800588 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800589 return -1;
590 }
591
592 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800593 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800594 deviceVersion = info.device_version;
595 } else {
596 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
597 }
598
599 if (facing) {
600 *facing = info.facing;
601 }
602
603 return deviceVersion;
604}
605
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700606status_t CameraService::filterGetInfoErrorCode(status_t err) {
607 switch(err) {
608 case NO_ERROR:
609 case -EINVAL:
610 return err;
611 default:
612 break;
613 }
614 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800615}
616
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800617bool CameraService::setUpVendorTags() {
618 vendor_tag_ops_t vOps = vendor_tag_ops_t();
619
620 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800621 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800622 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
623 return false;
624 }
625
626 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800627 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800628 ATRACE_END();
629
630 // Ensure all vendor operations are present
631 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
632 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
633 vOps.get_tag_type == NULL) {
634 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
635 , __FUNCTION__);
636 return false;
637 }
638
639 // Read all vendor tag definitions into a descriptor
640 sp<VendorTagDescriptor> desc;
641 status_t res;
642 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
643 != OK) {
644 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
645 "received error %s (%d). Camera clients will not be able to use"
646 "vendor tags", __FUNCTION__, strerror(res), res);
647 return false;
648 }
649
650 // Set the global descriptor to use with camera metadata
651 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
652 return true;
653}
654
Ruben Brunkcc776712015-02-17 20:18:47 -0800655status_t CameraService::makeClient(const sp<CameraService>& cameraService,
656 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
657 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
658 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
659 /*out*/sp<BasicClient>* client) {
660
661 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
662 int id = cameraIdToInt(cameraId);
663 if (id == -1) {
664 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
665 cameraId.string());
666 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700667 }
668
Ruben Brunkcc776712015-02-17 20:18:47 -0800669 if (halVersion < 0 || halVersion == deviceVersion) {
670 // Default path: HAL version is unspecified by caller, create CameraClient
671 // based on device version reported by the HAL.
672 switch(deviceVersion) {
673 case CAMERA_DEVICE_API_VERSION_1_0:
674 if (effectiveApiLevel == API_1) { // Camera1 API route
675 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
676 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
677 clientPid, clientUid, getpid(), legacyMode);
678 } else { // Camera2 API route
679 ALOGW("Camera using old HAL version: %d", deviceVersion);
680 return -EOPNOTSUPP;
681 }
682 break;
683 case CAMERA_DEVICE_API_VERSION_2_0:
684 case CAMERA_DEVICE_API_VERSION_2_1:
685 case CAMERA_DEVICE_API_VERSION_3_0:
686 case CAMERA_DEVICE_API_VERSION_3_1:
687 case CAMERA_DEVICE_API_VERSION_3_2:
688 case CAMERA_DEVICE_API_VERSION_3_3:
689 if (effectiveApiLevel == API_1) { // Camera1 API route
690 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
691 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
692 clientPid, clientUid, servicePid, legacyMode);
693 } else { // Camera2 API route
694 sp<ICameraDeviceCallbacks> tmp =
695 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
696 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
697 facing, clientPid, clientUid, servicePid);
698 }
699 break;
700 default:
701 // Should not be reachable
702 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
703 return INVALID_OPERATION;
704 }
705 } else {
706 // A particular HAL version is requested by caller. Create CameraClient
707 // based on the requested HAL version.
708 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
709 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
710 // Only support higher HAL version device opened as HAL1.0 device.
711 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
712 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
713 clientPid, clientUid, servicePid, legacyMode);
714 } else {
715 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
716 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
717 " opened as HAL %x device", halVersion, deviceVersion,
718 CAMERA_DEVICE_API_VERSION_1_0);
719 return INVALID_OPERATION;
720 }
721 }
722 return NO_ERROR;
723}
724
Ruben Brunk6267b532015-04-30 17:44:07 -0700725String8 CameraService::toString(std::set<userid_t> intSet) {
726 String8 s("");
727 bool first = true;
728 for (userid_t i : intSet) {
729 if (first) {
730 s.appendFormat("%d", i);
731 first = false;
732 } else {
733 s.appendFormat(", %d", i);
734 }
735 }
736 return s;
737}
738
Ruben Brunkcc776712015-02-17 20:18:47 -0800739status_t CameraService::initializeShimMetadata(int cameraId) {
740 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700741
742 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800743 String8 id = String8::format("%d", cameraId);
744 status_t ret = NO_ERROR;
745 sp<Client> tmp = nullptr;
746 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
747 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
748 false, true, tmp)) != NO_ERROR) {
749 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
750 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700751 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800752 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700753}
754
Igor Murashkin65d14b92014-06-17 12:03:20 -0700755status_t CameraService::getLegacyParametersLazy(int cameraId,
756 /*out*/
757 CameraParameters* parameters) {
758
759 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
760
761 status_t ret = 0;
762
763 if (parameters == NULL) {
764 ALOGE("%s: parameters must not be null", __FUNCTION__);
765 return BAD_VALUE;
766 }
767
Ruben Brunkcc776712015-02-17 20:18:47 -0800768 String8 id = String8::format("%d", cameraId);
769
770 // Check if we already have parameters
771 {
772 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700773 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800774 auto cameraState = getCameraState(id);
775 if (cameraState == nullptr) {
776 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
777 return BAD_VALUE;
778 }
779 CameraParameters p = cameraState->getShimParams();
780 if (!p.isEmpty()) {
781 *parameters = p;
782 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700783 }
784 }
785
Ruben Brunkcc776712015-02-17 20:18:47 -0800786 int64_t token = IPCThreadState::self()->clearCallingIdentity();
787 ret = initializeShimMetadata(cameraId);
788 IPCThreadState::self()->restoreCallingIdentity(token);
789 if (ret != NO_ERROR) {
790 // Error already logged by callee
791 return ret;
792 }
793
794 // Check for parameters again
795 {
796 // Scope for service lock
797 Mutex::Autolock lock(mServiceLock);
798 auto cameraState = getCameraState(id);
799 if (cameraState == nullptr) {
800 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
801 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700802 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800803 CameraParameters p = cameraState->getShimParams();
804 if (!p.isEmpty()) {
805 *parameters = p;
806 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700807 }
808 }
809
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
811 __FUNCTION__);
812 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700813}
814
Ruben Brunk36597b22015-03-20 22:15:57 -0700815status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
816 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800817
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500819
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800820 if (clientUid == USE_CALLING_UID) {
821 clientUid = getCallingUid();
822 } else {
823 // We only trust our own process to forward client UIDs
824 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700825 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
826 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700827 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800828 }
829 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830
Iliyan Malchev8951a972011-04-14 16:55:59 -0700831 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
833 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700834 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700835 }
836
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 if (getCameraState(cameraId) == nullptr) {
838 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
839 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700840 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841 }
842
Ruben Brunkcc776712015-02-17 20:18:47 -0800843 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800844 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800845 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700846 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800847 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
848 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800849 if (strcmp(value, "1") == 0) {
850 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800851 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
852 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700853 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800854 }
855
Ruben Brunka8ca9152015-04-07 14:23:40 -0700856 // Only allow clients who are being used by the current foreground device user, unless calling
857 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700858 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
859 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
860 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
861 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700862 return PERMISSION_DENIED;
863 }
864
Ruben Brunkcc776712015-02-17 20:18:47 -0800865 return checkIfDeviceIsUsable(cameraId);
866}
867
868status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
869 auto cameraState = getCameraState(cameraId);
870 int callingPid = getCallingPid();
871 if (cameraState == nullptr) {
872 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
873 cameraId.string());
874 return -ENODEV;
875 }
876
877 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700878 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800879 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
880 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700881 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700882 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800883 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
884 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700885 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700886 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700887
Ruben Brunkcc776712015-02-17 20:18:47 -0800888 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800889}
890
Ruben Brunkcc776712015-02-17 20:18:47 -0800891void CameraService::finishConnectLocked(const sp<BasicClient>& client,
892 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800893
Ruben Brunkcc776712015-02-17 20:18:47 -0800894 // Make a descriptor for the incoming client
895 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
896 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
897
898 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
899 String8(client->getPackageName()));
900
901 if (evicted.size() > 0) {
902 // This should never happen - clients should already have been removed in disconnect
903 for (auto& i : evicted) {
904 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
905 __FUNCTION__, i->getKey().string());
906 }
907
908 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
909 __FUNCTION__);
910 }
911}
912
913status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
914 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
915 /*out*/
916 sp<BasicClient>* client,
917 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
918
919 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700920 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800921 DescriptorPtr clientDescriptor;
922 {
923 if (effectiveApiLevel == API_1) {
924 // If we are using API1, any existing client for this camera ID with the same remote
925 // should be returned rather than evicted to allow MediaRecorder to work properly.
926
927 auto current = mActiveClientManager.get(cameraId);
928 if (current != nullptr) {
929 auto clientSp = current->getValue();
930 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700931 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
932 ALOGW("CameraService connect called from same client, but with a different"
933 " API level, evicting prior client...");
934 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800935 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700936 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800937 *client = clientSp;
938 return NO_ERROR;
939 }
940 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800941 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800942 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800943
Ruben Brunkcc776712015-02-17 20:18:47 -0800944 // Return error if the device was unplugged or removed by the HAL for some reason
945 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
946 return ret;
947 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800948
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 // Get current active client PIDs
950 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
951 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800952
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700953 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
954 // address of PROCESS_STATE_NONEXISTENT as a reference argument
955 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
956 // not have an out-of-class definition.
957 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800958
Ruben Brunkcc776712015-02-17 20:18:47 -0800959 // Get priorites of all active PIDs
960 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
961 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700962
Ruben Brunkcc776712015-02-17 20:18:47 -0800963 // Update all active clients' priorities
964 std::map<int,int> pidToPriorityMap;
965 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
966 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
967 }
968 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800969
Ruben Brunkcc776712015-02-17 20:18:47 -0800970 // Get state for the given cameraId
971 auto state = getCameraState(cameraId);
972 if (state == nullptr) {
973 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
974 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700975 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -0700976 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800977
978 // Make descriptor for incoming client
979 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
980 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
981 state->getConflicting(),
982 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
983
984 // Find clients that would be evicted
985 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
986
987 // If the incoming client was 'evicted,' higher priority clients have the camera in the
988 // background, so we cannot do evictions
989 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
990 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
991 " priority).", clientPid);
992
993 sp<BasicClient> clientSp = clientDescriptor->getValue();
994 String8 curTime = getFormattedCurrentTime();
995 auto incompatibleClients =
996 mActiveClientManager.getIncompatibleClients(clientDescriptor);
997
998 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -0700999 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001000 cameraId.string(), packageName.string(), clientPid,
1001 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1002
1003 for (auto& i : incompatibleClients) {
1004 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1005 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1006 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1007 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001008 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1009 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1010 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1011 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001012 }
1013
1014 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001015 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001016 mEventLog.add(msg);
1017
1018 return -EBUSY;
1019 }
1020
1021 for (auto& i : evicted) {
1022 sp<BasicClient> clientSp = i->getValue();
1023 if (clientSp.get() == nullptr) {
1024 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1025
1026 // TODO: Remove this
1027 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1028 __FUNCTION__);
1029 mActiveClientManager.remove(i);
1030 continue;
1031 }
1032
1033 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1034 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001035 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001036
Ruben Brunkcc776712015-02-17 20:18:47 -08001037 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001038 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1039 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1040 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001041 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1042 i->getOwnerId(), i->getPriority(), cameraId.string(),
1043 packageName.string(), clientPid,
1044 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1045
1046 // Notify the client of disconnection
1047 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1048 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001049 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001050 }
1051
Ruben Brunkcc776712015-02-17 20:18:47 -08001052 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1053 // other clients from connecting in mServiceLockWrapper if held
1054 mServiceLock.unlock();
1055
1056 // Clear caller identity temporarily so client disconnect PID checks work correctly
1057 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1058
1059 // Destroy evicted clients
1060 for (auto& i : evictedClients) {
1061 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001062 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001063 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001064
1065 IPCThreadState::self()->restoreCallingIdentity(token);
1066
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001067 for (const auto& i : evictedClients) {
1068 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1069 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1070 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1071 if (ret == TIMED_OUT) {
1072 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1073 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1074 mActiveClientManager.toString().string());
1075 return -EBUSY;
1076 }
1077 if (ret != NO_ERROR) {
1078 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1079 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1080 ret, mActiveClientManager.toString().string());
1081 return ret;
1082 }
1083 }
1084
1085 evictedClients.clear();
1086
Ruben Brunkcc776712015-02-17 20:18:47 -08001087 // Once clients have been disconnected, relock
1088 mServiceLock.lock();
1089
1090 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1091 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1092 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001093 }
1094
Ruben Brunkcc776712015-02-17 20:18:47 -08001095 *partial = clientDescriptor;
1096 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001097}
1098
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001099status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001100 const sp<ICameraClient>& cameraClient,
1101 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001102 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001103 int clientUid,
1104 /*out*/
1105 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001106
Ruben Brunkcc776712015-02-17 20:18:47 -08001107 status_t ret = NO_ERROR;
1108 String8 id = String8::format("%d", cameraId);
1109 sp<Client> client = nullptr;
1110 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001111 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001112
Ruben Brunkcc776712015-02-17 20:18:47 -08001113 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001114 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001115 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001116 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 }
1118
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001119 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001120 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121}
1122
Zhijun Heb10cdad2014-06-16 16:38:35 -07001123status_t CameraService::connectLegacy(
1124 const sp<ICameraClient>& cameraClient,
1125 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001126 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001127 int clientUid,
1128 /*out*/
1129 sp<ICamera>& device) {
1130
Ruben Brunka8ca9152015-04-07 14:23:40 -07001131 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001132 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001133 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001134 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001135 /*
1136 * Either the HAL version is unspecified in which case this just creates
1137 * a camera client selected by the latest device version, or
1138 * it's a particular version in which case the HAL must supported
1139 * the open_legacy call
1140 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001141 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001142 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001143 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001144 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001145 return INVALID_OPERATION;
1146 }
1147
Ruben Brunkcc776712015-02-17 20:18:47 -08001148 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001149 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001150 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001151 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001152
Ruben Brunkcc776712015-02-17 20:18:47 -08001153 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001154 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001155 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001156 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001157 }
1158
Zhijun Heb10cdad2014-06-16 16:38:35 -07001159 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001160 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001161}
1162
Ruben Brunkcc776712015-02-17 20:18:47 -08001163status_t CameraService::connectDevice(
1164 const sp<ICameraDeviceCallbacks>& cameraCb,
1165 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001166 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001167 int clientUid,
1168 /*out*/
1169 sp<ICameraDeviceUser>& device) {
1170
1171 status_t ret = NO_ERROR;
1172 String8 id = String8::format("%d", cameraId);
1173 sp<CameraDeviceClient> client = nullptr;
1174 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001175 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001176 /*out*/client);
1177
1178 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001179 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001180 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001181 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001182 }
1183
Ruben Brunkcc776712015-02-17 20:18:47 -08001184 device = client;
1185 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001186}
1187
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001188status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1189 const sp<IBinder>& clientBinder) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001190 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001191 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001192 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001193 }
1194
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001195 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001196 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001197
1198 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001199 auto state = getCameraState(id);
1200 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001201 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001202 return -EINVAL;
1203 }
1204
1205 ICameraServiceListener::Status cameraStatus = state->getStatus();
1206 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1207 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001208 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001209 return -EINVAL;
1210 }
1211
1212 {
1213 Mutex::Autolock al(mTorchStatusMutex);
1214 ICameraServiceListener::TorchStatus status;
1215 status_t res = getTorchStatusLocked(id, &status);
1216 if (res) {
1217 ALOGE("%s: getting current torch status failed for camera %s",
1218 __FUNCTION__, id.string());
1219 return -EINVAL;
1220 }
1221
1222 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001223 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001224 ALOGE("%s: torch mode of camera %s is not available because "
1225 "camera is in use", __FUNCTION__, id.string());
1226 return -EBUSY;
1227 } else {
1228 ALOGE("%s: torch mode of camera %s is not available due to "
1229 "insufficient resources", __FUNCTION__, id.string());
1230 return -EUSERS;
1231 }
1232 }
1233 }
1234
Ruben Brunk99e69712015-05-26 17:25:07 -07001235 {
1236 // Update UID map - this is used in the torch status changed callbacks, so must be done
1237 // before setTorchMode
1238 Mutex::Autolock al(mTorchClientMapMutex);
1239 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1240 mTorchUidMap[id].first = uid;
1241 mTorchUidMap[id].second = uid;
1242 } else {
1243 // Set the pending UID
1244 mTorchUidMap[id].first = uid;
1245 }
1246 }
1247
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001248 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001249
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001250 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001251 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1252 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001253 return res;
1254 }
1255
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001256 {
1257 // update the link to client's death
1258 Mutex::Autolock al(mTorchClientMapMutex);
1259 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001260 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001261 if (enabled) {
1262 if (index == NAME_NOT_FOUND) {
1263 mTorchClientMap.add(id, clientBinder);
1264 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001265 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001266 mTorchClientMap.replaceValueAt(index, clientBinder);
1267 }
1268 clientBinder->linkToDeath(this);
1269 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001270 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001271 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001272 }
1273
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001274 return OK;
1275}
1276
Ruben Brunk6267b532015-04-30 17:44:07 -07001277void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001278 switch(eventId) {
1279 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001280 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001281 break;
1282 }
1283 case ICameraService::NO_EVENT:
1284 default: {
1285 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1286 eventId);
1287 break;
1288 }
1289 }
1290}
1291
Ruben Brunk99e69712015-05-26 17:25:07 -07001292status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001293 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001294
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001295 if (listener == 0) {
1296 ALOGE("%s: Listener must not be null", __FUNCTION__);
1297 return BAD_VALUE;
1298 }
1299
Igor Murashkinbfc99152013-02-27 12:55:20 -08001300 Mutex::Autolock lock(mServiceLock);
1301
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 {
1303 Mutex::Autolock lock(mStatusListenerLock);
1304 for (auto& it : mListenerList) {
1305 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1306 ALOGW("%s: Tried to add listener %p which was already subscribed",
1307 __FUNCTION__, listener.get());
1308 return ALREADY_EXISTS;
1309 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001310 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001311
1312 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001313 }
1314
Igor Murashkinbfc99152013-02-27 12:55:20 -08001315
Igor Murashkincba2c162013-03-20 15:56:31 -07001316 /* Immediately signal current status to this listener only */
1317 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001318 Mutex::Autolock lock(mCameraStatesLock);
1319 for (auto& i : mCameraStates) {
1320 // TODO: Update binder to use String16 for camera IDs and remove;
1321 int id = cameraIdToInt(i.first);
1322 if (id == -1) continue;
1323
1324 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001325 }
1326 }
1327
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001328 /* Immediately signal current torch status to this listener only */
1329 {
1330 Mutex::Autolock al(mTorchStatusMutex);
1331 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001332 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1333 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001334 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001335 }
1336
Igor Murashkinbfc99152013-02-27 12:55:20 -08001337 return OK;
1338}
Ruben Brunkcc776712015-02-17 20:18:47 -08001339
1340status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001341 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1342
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001343 if (listener == 0) {
1344 ALOGE("%s: Listener must not be null", __FUNCTION__);
1345 return BAD_VALUE;
1346 }
1347
Igor Murashkinbfc99152013-02-27 12:55:20 -08001348 Mutex::Autolock lock(mServiceLock);
1349
Ruben Brunkcc776712015-02-17 20:18:47 -08001350 {
1351 Mutex::Autolock lock(mStatusListenerLock);
1352 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1353 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1354 mListenerList.erase(it);
1355 return OK;
1356 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001357 }
1358 }
1359
1360 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1361 __FUNCTION__, listener.get());
1362
1363 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001364}
1365
Ruben Brunkcc776712015-02-17 20:18:47 -08001366status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001367 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1368
1369 if (parameters == NULL) {
1370 ALOGE("%s: parameters must not be null", __FUNCTION__);
1371 return BAD_VALUE;
1372 }
1373
1374 status_t ret = 0;
1375
1376 CameraParameters shimParams;
1377 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1378 // Error logged by caller
1379 return ret;
1380 }
1381
1382 String8 shimParamsString8 = shimParams.flatten();
1383 String16 shimParamsString16 = String16(shimParamsString8);
1384
1385 *parameters = shimParamsString16;
1386
1387 return OK;
1388}
1389
1390status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1391 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1392
1393 switch (apiVersion) {
1394 case API_VERSION_1:
1395 case API_VERSION_2:
1396 break;
1397 default:
1398 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1399 return BAD_VALUE;
1400 }
1401
1402 int facing = -1;
1403 int deviceVersion = getDeviceVersion(cameraId, &facing);
1404
1405 switch(deviceVersion) {
1406 case CAMERA_DEVICE_API_VERSION_1_0:
1407 case CAMERA_DEVICE_API_VERSION_2_0:
1408 case CAMERA_DEVICE_API_VERSION_2_1:
1409 case CAMERA_DEVICE_API_VERSION_3_0:
1410 case CAMERA_DEVICE_API_VERSION_3_1:
1411 if (apiVersion == API_VERSION_2) {
1412 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1413 __FUNCTION__, cameraId);
1414 return -EOPNOTSUPP;
1415 } else { // if (apiVersion == API_VERSION_1) {
1416 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1417 __FUNCTION__, cameraId);
1418 return OK;
1419 }
1420 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001421 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001422 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1423 __FUNCTION__, cameraId);
1424 return OK;
1425 case -1:
1426 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1427 return BAD_VALUE;
1428 default:
1429 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1430 return INVALID_OPERATION;
1431 }
1432
1433 return OK;
1434}
1435
Ruben Brunkcc776712015-02-17 20:18:47 -08001436void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001437 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 for (auto& i : mActiveClientManager.getAll()) {
1439 auto clientSp = i->getValue();
1440 if (clientSp.get() == client) {
1441 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001442 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001443 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001444}
1445
Ruben Brunkcc776712015-02-17 20:18:47 -08001446bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1447 const int callingPid = getCallingPid();
1448 const int servicePid = getpid();
1449 bool ret = false;
1450 {
1451 // Acquire mServiceLock and prevent other clients from connecting
1452 std::unique_ptr<AutoConditionLock> lock =
1453 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001454
Igor Murashkin634a5152013-02-20 17:15:11 -08001455
Ruben Brunkcc776712015-02-17 20:18:47 -08001456 std::vector<sp<BasicClient>> evicted;
1457 for (auto& i : mActiveClientManager.getAll()) {
1458 auto clientSp = i->getValue();
1459 if (clientSp.get() == nullptr) {
1460 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1461 mActiveClientManager.remove(i);
1462 continue;
1463 }
1464 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1465 callingPid == clientSp->getClientPid())) {
1466 mActiveClientManager.remove(i);
1467 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001468
Ruben Brunkcc776712015-02-17 20:18:47 -08001469 // Notify the client of disconnection
1470 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1471 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001472 }
1473 }
1474
Ruben Brunkcc776712015-02-17 20:18:47 -08001475 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1476 // other clients from connecting in mServiceLockWrapper if held
1477 mServiceLock.unlock();
1478
Ruben Brunk36597b22015-03-20 22:15:57 -07001479 // Do not clear caller identity, remote caller should be client proccess
1480
Ruben Brunkcc776712015-02-17 20:18:47 -08001481 for (auto& i : evicted) {
1482 if (i.get() != nullptr) {
1483 i->disconnect();
1484 ret = true;
1485 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001486 }
1487
Ruben Brunkcc776712015-02-17 20:18:47 -08001488 // Reacquire mServiceLock
1489 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001490
Ruben Brunkcc776712015-02-17 20:18:47 -08001491 } // lock is destroyed, allow further connect calls
1492
1493 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001494}
1495
Igor Murashkinecf17e82012-10-02 16:05:11 -07001496
Ruben Brunkcc776712015-02-17 20:18:47 -08001497std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1498 const String8& cameraId) const {
1499 std::shared_ptr<CameraState> state;
1500 {
1501 Mutex::Autolock lock(mCameraStatesLock);
1502 auto iter = mCameraStates.find(cameraId);
1503 if (iter != mCameraStates.end()) {
1504 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 }
1506 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001507 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508}
1509
Ruben Brunkcc776712015-02-17 20:18:47 -08001510sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1511 // Remove from active clients list
1512 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1513 if (clientDescriptorPtr == nullptr) {
1514 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1515 cameraId.string());
1516 return sp<BasicClient>{nullptr};
1517 }
1518
1519 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001520}
1521
Ruben Brunk6267b532015-04-30 17:44:07 -07001522void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001523 // Acquire mServiceLock and prevent other clients from connecting
1524 std::unique_ptr<AutoConditionLock> lock =
1525 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1526
Ruben Brunk6267b532015-04-30 17:44:07 -07001527 std::set<userid_t> newAllowedUsers;
1528 for (size_t i = 0; i < length; i++) {
1529 if (newUserId[i] < 0) {
1530 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1531 __FUNCTION__, newUserId[i]);
1532 return;
1533 }
1534 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001535 }
1536
Ruben Brunka8ca9152015-04-07 14:23:40 -07001537
Ruben Brunk6267b532015-04-30 17:44:07 -07001538 if (newAllowedUsers == mAllowedUsers) {
1539 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1540 return;
1541 }
1542
1543 logUserSwitch(mAllowedUsers, newAllowedUsers);
1544
1545 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001546
1547 // Current user has switched, evict all current clients.
1548 std::vector<sp<BasicClient>> evicted;
1549 for (auto& i : mActiveClientManager.getAll()) {
1550 auto clientSp = i->getValue();
1551
1552 if (clientSp.get() == nullptr) {
1553 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1554 continue;
1555 }
1556
Ruben Brunk6267b532015-04-30 17:44:07 -07001557 // Don't evict clients that are still allowed.
1558 uid_t clientUid = clientSp->getClientUid();
1559 userid_t clientUserId = multiuser_get_user_id(clientUid);
1560 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1561 continue;
1562 }
1563
Ruben Brunk36597b22015-03-20 22:15:57 -07001564 evicted.push_back(clientSp);
1565
1566 String8 curTime = getFormattedCurrentTime();
1567
1568 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1569 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001570
Ruben Brunk36597b22015-03-20 22:15:57 -07001571 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001572 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001573 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001574 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1575 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001576
1577 }
1578
1579 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1580 // blocking other clients from connecting in mServiceLockWrapper if held.
1581 mServiceLock.unlock();
1582
1583 // Clear caller identity temporarily so client disconnect PID checks work correctly
1584 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1585
1586 for (auto& i : evicted) {
1587 i->disconnect();
1588 }
1589
1590 IPCThreadState::self()->restoreCallingIdentity(token);
1591
1592 // Reacquire mServiceLock
1593 mServiceLock.lock();
1594}
Ruben Brunkcc776712015-02-17 20:18:47 -08001595
Ruben Brunka8ca9152015-04-07 14:23:40 -07001596void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001597 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001598 Mutex::Autolock l(mLogLock);
1599 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600}
1601
Ruben Brunka8ca9152015-04-07 14:23:40 -07001602void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001603 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001604 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001605 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001606 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001607}
1608
1609void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001610 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001611 // Log the clients evicted
1612 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001613 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001614}
1615
1616void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001617 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001618 // Log the client rejected
1619 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001620 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001621}
1622
Ruben Brunk6267b532015-04-30 17:44:07 -07001623void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1624 const std::set<userid_t>& newUserIds) {
1625 String8 newUsers = toString(newUserIds);
1626 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001627 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001628 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1629 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001630}
1631
1632void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1633 // Log the device removal
1634 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1635}
1636
1637void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1638 // Log the device removal
1639 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1640}
1641
1642void CameraService::logClientDied(int clientPid, const char* reason) {
1643 // Log the device removal
1644 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001645}
1646
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001647void CameraService::logServiceError(const char* msg, int errorCode) {
1648 String8 curTime = getFormattedCurrentTime();
1649 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1650}
1651
Ruben Brunk36597b22015-03-20 22:15:57 -07001652status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1653 uint32_t flags) {
1654
1655 const int pid = getCallingPid();
1656 const int selfPid = getpid();
1657
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 // Permission checks
1659 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001660 case BnCameraService::CONNECT:
1661 case BnCameraService::CONNECT_DEVICE:
1662 case BnCameraService::CONNECT_LEGACY: {
1663 if (pid != selfPid) {
1664 // we're called from a different process, do the real check
1665 if (!checkCallingPermission(
1666 String16("android.permission.CAMERA"))) {
1667 const int uid = getCallingUid();
1668 ALOGE("Permission Denial: "
1669 "can't use the camera pid=%d, uid=%d", pid, uid);
1670 return PERMISSION_DENIED;
1671 }
1672 }
1673 break;
1674 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001675 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1676 if (pid != selfPid) {
1677 // Ensure we're being called by system_server, or similar process with
1678 // permissions to notify the camera service about system events
1679 if (!checkCallingPermission(
1680 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1681 const int uid = getCallingUid();
1682 ALOGE("Permission Denial: cannot send updates to camera service about system"
1683 " events from pid=%d, uid=%d", pid, uid);
1684 return PERMISSION_DENIED;
1685 }
1686 }
1687 break;
1688 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 }
1690
1691 return BnCameraService::onTransact(code, data, reply, flags);
1692}
1693
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694// We share the media players for shutter and recording sound for all clients.
1695// A reference count is kept to determine when we will actually release the
1696// media players.
1697
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001698MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001700 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001701 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702 mp->prepare();
1703 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001704 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 return NULL;
1706 }
1707 return mp;
1708}
1709
1710void CameraService::loadSound() {
1711 Mutex::Autolock lock(mSoundLock);
1712 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1713 if (mSoundRef++) return;
1714
1715 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1716 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1717}
1718
1719void CameraService::releaseSound() {
1720 Mutex::Autolock lock(mSoundLock);
1721 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1722 if (--mSoundRef) return;
1723
1724 for (int i = 0; i < NUM_SOUNDS; i++) {
1725 if (mSoundPlayer[i] != 0) {
1726 mSoundPlayer[i]->disconnect();
1727 mSoundPlayer[i].clear();
1728 }
1729 }
1730}
1731
1732void CameraService::playSound(sound_kind kind) {
1733 LOG1("playSound(%d)", kind);
1734 Mutex::Autolock lock(mSoundLock);
1735 sp<MediaPlayer> player = mSoundPlayer[kind];
1736 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001737 player->seekTo(0);
1738 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739 }
1740}
1741
1742// ----------------------------------------------------------------------------
1743
1744CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001745 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001746 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001747 int cameraId, int cameraFacing,
1748 int clientPid, uid_t clientUid,
1749 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001750 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001751 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001752 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001753 cameraId, cameraFacing,
1754 clientPid, clientUid,
1755 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001756{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001758 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001760 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001763
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001764 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765}
1766
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767// tear down the client
1768CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001769 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001770 mDestructionStarted = true;
1771
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001772 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001773 // unconditionally disconnect. function is idempotent
1774 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775}
1776
Igor Murashkin634a5152013-02-20 17:15:11 -08001777CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001778 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001779 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001780 int cameraId, int cameraFacing,
1781 int clientPid, uid_t clientUid,
1782 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001783 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001784{
1785 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001786 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001787 mCameraId = cameraId;
1788 mCameraFacing = cameraFacing;
1789 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001790 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001791 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001792 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001793 mDestructionStarted = false;
1794}
1795
1796CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001797 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001798 mDestructionStarted = true;
1799}
1800
1801void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001802 if (mDisconnected) {
1803 ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1804 mCameraId);
1805 return;
1806 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001807 mDisconnected = true;;
1808
1809 mCameraService->removeByClient(this);
1810 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001811 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001812
1813 sp<IBinder> remote = getRemote();
1814 if (remote != nullptr) {
1815 remote->unlinkToDeath(mCameraService);
1816 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001817
1818 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001819 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1820
Igor Murashkincba2c162013-03-20 15:56:31 -07001821 // client shouldn't be able to call into us anymore
1822 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001823}
1824
Ruben Brunkcc776712015-02-17 20:18:47 -08001825String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001826 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001827}
1828
1829
1830int CameraService::BasicClient::getClientPid() const {
1831 return mClientPid;
1832}
1833
Ruben Brunk6267b532015-04-30 17:44:07 -07001834uid_t CameraService::BasicClient::getClientUid() const {
1835 return mClientUid;
1836}
1837
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001838bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1839 // Defaults to API2.
1840 return level == API_2;
1841}
1842
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001843status_t CameraService::BasicClient::startCameraOps() {
1844 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001845 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001846 mOpsCallback = new OpsCallback(this);
1847
Igor Murashkine6800ce2013-03-04 17:25:57 -08001848 {
1849 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001850 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001851 }
1852
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001853 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001854 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001855 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001856 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001857
Svetoslav28e8ef72015-05-11 19:21:31 -07001858 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001859 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001860 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001861 return PERMISSION_DENIED;
1862 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001863
Svetoslav28e8ef72015-05-11 19:21:31 -07001864 if (res == AppOpsManager::MODE_IGNORED) {
1865 ALOGI("Camera %d: Access for \"%s\" has been restricted",
1866 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07001867 // Return the same error as for device policy manager rejection
1868 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07001869 }
1870
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001871 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001872
1873 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1874 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001875 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001876
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001877 return OK;
1878}
1879
1880status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001881 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001882 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001883 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001884 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001885 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001886 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001887
Ruben Brunkcc776712015-02-17 20:18:47 -08001888 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1889 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001890
Ruben Brunkcc776712015-02-17 20:18:47 -08001891 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001892 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001894
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001895 // Notify flashlight that a camera device is closed.
1896 mCameraService->mFlashlight->deviceClosed(
1897 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001898 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001899 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001900 if (mOpsCallback != NULL) {
1901 mAppOpsManager.stopWatchingMode(mOpsCallback);
1902 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001903 mOpsCallback.clear();
1904
1905 return OK;
1906}
1907
1908void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1909 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001910 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001911
1912 if (op != AppOpsManager::OP_CAMERA) {
1913 ALOGW("Unexpected app ops notification received: %d", op);
1914 return;
1915 }
1916
1917 int32_t res;
1918 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001919 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001920 ALOGV("checkOp returns: %d, %s ", res,
1921 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1922 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1923 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1924 "UNKNOWN");
1925
1926 if (res != AppOpsManager::MODE_ALLOWED) {
1927 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1928 myName.string());
1929 // Reset the client PID to allow server-initiated disconnect,
1930 // and to prevent further calls by client.
1931 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07001932 CaptureResultExtras resultExtras; // a dummy result (invalid)
1933 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001934 disconnect();
1935 }
1936}
1937
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938// ----------------------------------------------------------------------------
1939
Ruben Brunkcc776712015-02-17 20:18:47 -08001940// Provide client strong pointer for callbacks.
1941sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
1942 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
1943 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
1944 if (clientDescriptor != nullptr) {
1945 return sp<Client>{
1946 static_cast<Client*>(clientDescriptor->getValue().get())};
1947 }
1948 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949}
1950
Jianing Weicb0652e2014-03-12 18:29:36 -07001951void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1952 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001953 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001954}
1955
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001956// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07001957void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001958 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08001959 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08001960}
1961
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001962bool CameraService::Client::canCastToApiClient(apiLevel level) const {
1963 return level == API_1;
1964}
1965
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001966CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1967 mClient(client) {
1968}
1969
1970void CameraService::Client::OpsCallback::opChanged(int32_t op,
1971 const String16& packageName) {
1972 sp<BasicClient> client = mClient.promote();
1973 if (client != NULL) {
1974 client->opChanged(op, packageName);
1975 }
1976}
1977
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08001979// CameraState
1980// ----------------------------------------------------------------------------
1981
1982CameraService::CameraState::CameraState(const String8& id, int cost,
1983 const std::set<String8>& conflicting) : mId(id),
1984 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
1985
1986CameraService::CameraState::~CameraState() {}
1987
1988ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
1989 Mutex::Autolock lock(mStatusLock);
1990 return mStatus;
1991}
1992
1993CameraParameters CameraService::CameraState::getShimParams() const {
1994 return mShimParams;
1995}
1996
1997void CameraService::CameraState::setShimParams(const CameraParameters& params) {
1998 mShimParams = params;
1999}
2000
2001int CameraService::CameraState::getCost() const {
2002 return mCost;
2003}
2004
2005std::set<String8> CameraService::CameraState::getConflicting() const {
2006 return mConflicting;
2007}
2008
2009String8 CameraService::CameraState::getId() const {
2010 return mId;
2011}
2012
2013// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002014// ClientEventListener
2015// ----------------------------------------------------------------------------
2016
2017void CameraService::ClientEventListener::onClientAdded(
2018 const resource_policy::ClientDescriptor<String8,
2019 sp<CameraService::BasicClient>>& descriptor) {
2020 auto basicClient = descriptor.getValue();
2021 if (basicClient.get() != nullptr) {
2022 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2023 notifier.noteStartCamera(descriptor.getKey(),
2024 static_cast<int>(basicClient->getClientUid()));
2025 }
2026}
2027
2028void CameraService::ClientEventListener::onClientRemoved(
2029 const resource_policy::ClientDescriptor<String8,
2030 sp<CameraService::BasicClient>>& descriptor) {
2031 auto basicClient = descriptor.getValue();
2032 if (basicClient.get() != nullptr) {
2033 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2034 notifier.noteStopCamera(descriptor.getKey(),
2035 static_cast<int>(basicClient->getClientUid()));
2036 }
2037}
2038
2039
2040// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002041// CameraClientManager
2042// ----------------------------------------------------------------------------
2043
Ruben Brunk99e69712015-05-26 17:25:07 -07002044CameraService::CameraClientManager::CameraClientManager() {
2045 setListener(std::make_shared<ClientEventListener>());
2046}
2047
Ruben Brunkcc776712015-02-17 20:18:47 -08002048CameraService::CameraClientManager::~CameraClientManager() {}
2049
2050sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2051 const String8& id) const {
2052 auto descriptor = get(id);
2053 if (descriptor == nullptr) {
2054 return sp<BasicClient>{nullptr};
2055 }
2056 return descriptor->getValue();
2057}
2058
2059String8 CameraService::CameraClientManager::toString() const {
2060 auto all = getAll();
2061 String8 ret("[");
2062 bool hasAny = false;
2063 for (auto& i : all) {
2064 hasAny = true;
2065 String8 key = i->getKey();
2066 int32_t cost = i->getCost();
2067 int32_t pid = i->getOwnerId();
2068 int32_t priority = i->getPriority();
2069 auto conflicting = i->getConflicting();
2070 auto clientSp = i->getValue();
2071 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002072 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002073 if (clientSp.get() != nullptr) {
2074 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002075 uid_t clientUid = clientSp->getClientUid();
2076 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002077 }
2078 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2079 PRId32 ", ", key.string(), cost, pid, priority);
2080
Ruben Brunk6267b532015-04-30 17:44:07 -07002081 if (clientSp.get() != nullptr) {
2082 ret.appendFormat("User Id: %d, ", clientUserId);
2083 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002084 if (packageName.size() != 0) {
2085 ret.appendFormat("Client Package Name: %s", packageName.string());
2086 }
2087
2088 ret.append(", Conflicting Client Devices: {");
2089 for (auto& j : conflicting) {
2090 ret.appendFormat("%s, ", j.string());
2091 }
2092 ret.append("})");
2093 }
2094 if (hasAny) ret.append("\n");
2095 ret.append("]\n");
2096 return ret;
2097}
2098
2099CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2100 const String8& key, const sp<BasicClient>& value, int32_t cost,
2101 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2102
2103 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2104 key, value, cost, conflictingKeys, priority, ownerId);
2105}
2106
2107CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2108 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2109 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2110 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2111}
2112
2113// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114
2115static const int kDumpLockRetries = 50;
2116static const int kDumpLockSleep = 60000;
2117
2118static bool tryLock(Mutex& mutex)
2119{
2120 bool locked = false;
2121 for (int i = 0; i < kDumpLockRetries; ++i) {
2122 if (mutex.tryLock() == NO_ERROR) {
2123 locked = true;
2124 break;
2125 }
2126 usleep(kDumpLockSleep);
2127 }
2128 return locked;
2129}
2130
2131status_t CameraService::dump(int fd, const Vector<String16>& args) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002132 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002134 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 "can't dump CameraService from pid=%d, uid=%d\n",
2136 getCallingPid(),
2137 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 write(fd, result.string(), result.size());
2139 } else {
2140 bool locked = tryLock(mServiceLock);
2141 // failed to lock - CameraService is probably deadlocked
2142 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002143 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002144 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 }
2146
2147 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002148 if (!mModule) {
2149 result = String8::format("No camera module available!\n");
2150 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002151
2152 // Dump event log for error information
2153 dumpEventLog(fd);
2154
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002155 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002156 return NO_ERROR;
2157 }
2158
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002159 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2160 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2161 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2162 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002163 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2164 String8 activeClientString = mActiveClientManager.toString();
2165 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002166 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002167
Ruben Brunkf81648e2014-04-17 16:14:57 -07002168 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2169 if (desc == NULL) {
2170 result.appendFormat("Vendor tags left unimplemented.\n");
2171 } else {
2172 result.appendFormat("Vendor tag definitions:\n");
2173 }
2174
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002175 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002176
2177 if (desc != NULL) {
2178 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2179 }
2180
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002181 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002182
2183 bool stateLocked = tryLock(mCameraStatesLock);
2184 if (!stateLocked) {
2185 result = String8::format("CameraStates in use, may be deadlocked\n");
2186 write(fd, result.string(), result.size());
2187 }
2188
2189 for (auto& state : mCameraStates) {
2190 String8 cameraId = state.first;
2191 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002192 camera_info info;
2193
Ruben Brunkcc776712015-02-17 20:18:47 -08002194 // TODO: Change getCameraInfo + HAL to use String cameraIds
2195 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002196 if (rc != OK) {
2197 result.appendFormat(" Error reading static information!\n");
2198 write(fd, result.string(), result.size());
2199 } else {
2200 result.appendFormat(" Facing: %s\n",
2201 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2202 result.appendFormat(" Orientation: %d\n", info.orientation);
2203 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002204 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002205 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2206 } else {
2207 deviceVersion = info.device_version;
2208 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002209
2210 auto conflicting = state.second->getConflicting();
2211 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2212 result.appendFormat(" Conflicting Devices:");
2213 for (auto& id : conflicting) {
2214 result.appendFormat(" %s", cameraId.string());
2215 }
2216 if (conflicting.size() == 0) {
2217 result.appendFormat(" NONE");
2218 }
2219 result.appendFormat("\n");
2220
2221 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002222 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2223 result.appendFormat(" Device static metadata:\n");
2224 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002225 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002226 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002227 } else {
2228 write(fd, result.string(), result.size());
2229 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002230
2231 CameraParameters p = state.second->getShimParams();
2232 if (!p.isEmpty()) {
2233 result = String8::format(" Camera1 API shim is using parameters:\n ");
2234 write(fd, result.string(), result.size());
2235 p.dump(fd, args);
2236 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002237 }
2238
Ruben Brunkcc776712015-02-17 20:18:47 -08002239 auto clientDescriptor = mActiveClientManager.get(cameraId);
2240 if (clientDescriptor == nullptr) {
2241 result = String8::format(" Device %s is closed, no client instance\n",
2242 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002243 write(fd, result.string(), result.size());
2244 continue;
2245 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002247 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2248 cameraId.string());
2249 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2250 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2251
2252 auto client = clientDescriptor->getValue();
2253 result.appendFormat("Client package: %s\n",
2254 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002255 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002256
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002257 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002259
2260 if (stateLocked) mCameraStatesLock.unlock();
2261
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002263 result = String8::format("\nNo active camera clients yet.\n");
2264 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 }
2266
2267 if (locked) mServiceLock.unlock();
2268
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002269 // Dump camera traces if there were any
2270 write(fd, "\n", 1);
2271 camera3::CameraTraces::dump(fd, args);
2272
Mathias Agopian65ab4712010-07-14 17:59:35 -07002273 // change logging level
2274 int n = args.size();
2275 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002276 String16 verboseOption("-v");
2277 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 String8 levelStr(args[i+1]);
2279 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002280 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002282 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283 }
2284 }
2285 }
2286 return NO_ERROR;
2287}
2288
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002289void CameraService::dumpEventLog(int fd) {
2290 String8 result = String8("\nPrior client events (most recent at top):\n");
2291
2292 Mutex::Autolock l(mLogLock);
2293 for (const auto& msg : mEventLog) {
2294 result.appendFormat(" %s\n", msg.string());
2295 }
2296
2297 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2298 result.append(" ...\n");
2299 } else if (mEventLog.size() == 0) {
2300 result.append(" [no events yet]\n");
2301 }
2302 result.append("\n");
2303
2304 write(fd, result.string(), result.size());
2305}
2306
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002307void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002308 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002309 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2310 if (mTorchClientMap[i] == who) {
2311 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002312 String8 cameraId = mTorchClientMap.keyAt(i);
2313 status_t res = mFlashlight->setTorchMode(cameraId, false);
2314 if (res) {
2315 ALOGE("%s: torch client died but couldn't turn off torch: "
2316 "%s (%d)", __FUNCTION__, strerror(-res), res);
2317 return;
2318 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002319 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002320 break;
2321 }
2322 }
2323}
2324
Ruben Brunkcc776712015-02-17 20:18:47 -08002325/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002326
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002327 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002328 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2329 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002330 */
2331
Ruben Brunka8ca9152015-04-07 14:23:40 -07002332 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2333
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002334 // check torch client
2335 handleTorchClientBinderDied(who);
2336
2337 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002338 if(!evictClientIdByRemote(who)) {
2339 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002340 return;
2341 }
2342
Ruben Brunkcc776712015-02-17 20:18:47 -08002343 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2344 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002345}
2346
Ruben Brunkcc776712015-02-17 20:18:47 -08002347void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2348 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002349}
2350
Ruben Brunkcc776712015-02-17 20:18:47 -08002351void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2352 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2353 // Do not lock mServiceLock here or can get into a deadlock from
2354 // connect() -> disconnect -> updateStatus
2355
2356 auto state = getCameraState(cameraId);
2357
2358 if (state == nullptr) {
2359 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2360 cameraId.string());
2361 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002362 }
2363
Ruben Brunkcc776712015-02-17 20:18:47 -08002364 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2365 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2366 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2367 (const String8& cameraId, ICameraServiceListener::Status status) {
2368
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002369 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2370 // Update torch status if it has a flash unit.
2371 Mutex::Autolock al(mTorchStatusMutex);
2372 ICameraServiceListener::TorchStatus torchStatus;
2373 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2374 NAME_NOT_FOUND) {
2375 ICameraServiceListener::TorchStatus newTorchStatus =
2376 status == ICameraServiceListener::STATUS_PRESENT ?
2377 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2378 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2379 if (torchStatus != newTorchStatus) {
2380 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2381 }
2382 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002383 }
2384
2385 Mutex::Autolock lock(mStatusListenerLock);
2386
2387 for (auto& listener : mListenerList) {
2388 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2389 int id = cameraIdToInt(cameraId);
2390 if (id != -1) listener->onStatusChanged(status, id);
2391 }
2392 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002393}
2394
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002395status_t CameraService::getTorchStatusLocked(
2396 const String8& cameraId,
2397 ICameraServiceListener::TorchStatus *status) const {
2398 if (!status) {
2399 return BAD_VALUE;
2400 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002401 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2402 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002403 // invalid camera ID or the camera doesn't have a flash unit
2404 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002405 }
2406
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002407 *status = mTorchStatusMap.valueAt(index);
2408 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002409}
2410
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002411status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002412 ICameraServiceListener::TorchStatus status) {
2413 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2414 if (index == NAME_NOT_FOUND) {
2415 return BAD_VALUE;
2416 }
2417 ICameraServiceListener::TorchStatus& item =
2418 mTorchStatusMap.editValueAt(index);
2419 item = status;
2420
2421 return OK;
2422}
2423
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424}; // namespace android