blob: 527e80bdc351d83e7db8b8e7755a7ac34d88c8be [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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070037#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080038#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <hardware/hardware.h>
40#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080041#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070043#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <utils/Errors.h>
45#include <utils/Log.h>
46#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080047#include <utils/Trace.h>
48#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070049#include <system/camera_metadata.h>
50#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
52#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "api1/CameraClient.h"
54#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070055#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070056#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070057#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
59namespace android {
60
61// ----------------------------------------------------------------------------
62// Logging support -- this is for debugging only
63// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070064volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070065
Steve Blockb8a80522011-12-20 16:23:08 +000066#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
67#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070068
69static void setLogLevel(int level) {
70 android_atomic_write(level, &gLogLevel);
71}
72
73// ----------------------------------------------------------------------------
74
Igor Murashkincba2c162013-03-20 15:56:31 -070075extern "C" {
76static void camera_device_status_change(
77 const struct camera_module_callbacks* callbacks,
78 int camera_id,
79 int new_status) {
80 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080081 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070082
Ruben Brunkcc776712015-02-17 20:18:47 -080083 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
84 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070085}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080086
87static void torch_mode_status_change(
88 const struct camera_module_callbacks* callbacks,
89 const char* camera_id,
90 int new_status) {
91 if (!callbacks || !camera_id) {
92 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
93 callbacks, camera_id);
94 }
95 sp<CameraService> cs = const_cast<CameraService*>(
96 static_cast<const CameraService*>(callbacks));
97
98 ICameraServiceListener::TorchStatus status;
99 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800100 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800101 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
102 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800103 case TORCH_MODE_STATUS_AVAILABLE_OFF:
104 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
105 break;
106 case TORCH_MODE_STATUS_AVAILABLE_ON:
107 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800108 break;
109 default:
110 ALOGE("Unknown torch status %d", new_status);
111 return;
112 }
113
114 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800115 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800116 status);
117}
Igor Murashkincba2c162013-03-20 15:56:31 -0700118} // extern "C"
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
122// This is ugly and only safe if we never re-create the CameraService, but
123// should be ok for now.
124static CameraService *gCameraService;
125
Ruben Brunk6267b532015-04-30 17:44:07 -0700126CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH), mAllowedUsers(),
127 mSoundRef(0), mModule(0), mFlashlight(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000128 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800130
Igor Murashkincba2c162013-03-20 15:56:31 -0700131 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800132 this->torch_mode_status_change = android::torch_mode_status_change;
133
Ruben Brunkcc776712015-02-17 20:18:47 -0800134 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135}
136
Iliyan Malchev8951a972011-04-14 16:55:59 -0700137void CameraService::onFirstRef()
138{
Ruben Brunkcc776712015-02-17 20:18:47 -0800139 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800140
Iliyan Malchev8951a972011-04-14 16:55:59 -0700141 BnCameraService::onFirstRef();
142
Ruben Brunk99e69712015-05-26 17:25:07 -0700143 // Update battery life tracking if service is restarting
144 BatteryNotifier& notifier(BatteryNotifier::getInstance());
145 notifier.noteResetCamera();
146 notifier.noteResetFlashlight();
147
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800148 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700149 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
150 (const hw_module_t **)&rawModule);
151 if (err < 0) {
152 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
153 logServiceError("Could not load camera HAL module", err);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700154 mNumberOfCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700155 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700156 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800157
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700158 mModule = new CameraModule(rawModule);
159 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
160 err = mModule->init();
161 if (err != OK) {
162 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
163 strerror(-err));
164 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800165
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700166 mNumberOfCameras = 0;
167 delete mModule;
168 mModule = nullptr;
169 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700170 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700171
172 mNumberOfCameras = mModule->getNumberOfCameras();
173
174 mFlashlight = new CameraFlashlight(*mModule, *this);
175 status_t res = mFlashlight->findFlashUnits();
176 if (res) {
177 // impossible because we haven't open any camera devices.
178 ALOGE("Failed to find flash units.");
179 }
180
181 for (int i = 0; i < mNumberOfCameras; i++) {
182 String8 cameraId = String8::format("%d", i);
183
184 // Defaults to use for cost and conflicting devices
185 int cost = 100;
186 char** conflicting_devices = nullptr;
187 size_t conflicting_devices_length = 0;
188
189 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
190 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4) {
191 struct camera_info info;
192 status_t rc = mModule->getCameraInfo(i, &info);
193 if (rc == NO_ERROR) {
194 cost = info.resource_cost;
195 conflicting_devices = info.conflicting_devices;
196 conflicting_devices_length = info.conflicting_devices_length;
197 } else {
198 ALOGE("%s: Received error loading camera info for device %d, cost and"
199 " conflicting devices fields set to defaults for this device.",
200 __FUNCTION__, i);
201 }
202 }
203
204 std::set<String8> conflicting;
205 for (size_t i = 0; i < conflicting_devices_length; i++) {
206 conflicting.emplace(String8(conflicting_devices[i]));
207 }
208
209 // Initialize state for each camera device
210 {
211 Mutex::Autolock lock(mCameraStatesLock);
212 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
213 conflicting));
214 }
215
216 if (mFlashlight->hasFlashUnit(cameraId)) {
217 mTorchStatusMap.add(cameraId,
218 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
219 }
220 }
221
222 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
223 mModule->setCallbacks(this);
224 }
225
226 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
227
228 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
229 setUpVendorTags();
230 }
231
232 CameraDeviceFactory::registerService(this);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700233}
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800236 if (mModule) {
237 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800238 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800239 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800240 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800241 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242}
243
Ruben Brunkcc776712015-02-17 20:18:47 -0800244void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
245 camera_device_status_t newStatus) {
246 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700247 cameraId, newStatus);
248
Ruben Brunkcc776712015-02-17 20:18:47 -0800249 String8 id = String8::format("%d", cameraId);
250 std::shared_ptr<CameraState> state = getCameraState(id);
251
252 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700253 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
254 return;
255 }
256
Ruben Brunkcc776712015-02-17 20:18:47 -0800257 ICameraServiceListener::Status oldStatus = state->getStatus();
258
259 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
260 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700261 return;
262 }
263
Igor Murashkincba2c162013-03-20 15:56:31 -0700264 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700265 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
266 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800267 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700268 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800269 // Don't do this in updateStatus to avoid deadlock over mServiceLock
270 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700271
Ruben Brunkcc776712015-02-17 20:18:47 -0800272 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
273 // to this device until the status changes
274 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700275
Ruben Brunkcc776712015-02-17 20:18:47 -0800276 // Remove cached shim parameters
277 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700278
Ruben Brunkcc776712015-02-17 20:18:47 -0800279 // Remove the client from the list of active clients
280 clientToDisconnect = removeClientLocked(id);
281
282 // Notify the client of disconnection
283 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
284 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700285 }
286
Ruben Brunkcc776712015-02-17 20:18:47 -0800287 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
288 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700289
Ruben Brunkcc776712015-02-17 20:18:47 -0800290 // Disconnect client
291 if (clientToDisconnect.get() != nullptr) {
292 // Ensure not in binder RPC so client disconnect PID checks work correctly
293 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
294 "onDeviceStatusChanged must be called from the camera service process!");
295 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700296 }
297
Ruben Brunkcc776712015-02-17 20:18:47 -0800298 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700299 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
300 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
301 newStatus));
302 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800303 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700304 }
305
Igor Murashkincba2c162013-03-20 15:56:31 -0700306}
307
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800308void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800309 ICameraServiceListener::TorchStatus newStatus) {
310 Mutex::Autolock al(mTorchStatusMutex);
311 onTorchStatusChangedLocked(cameraId, newStatus);
312}
313
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800314void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800315 ICameraServiceListener::TorchStatus newStatus) {
316 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
317 __FUNCTION__, cameraId.string(), newStatus);
318
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800319 ICameraServiceListener::TorchStatus status;
320 status_t res = getTorchStatusLocked(cameraId, &status);
321 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700322 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
323 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800324 return;
325 }
326 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800327 return;
328 }
329
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800330 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800331 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700332 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800333 return;
334 }
335
Ruben Brunkcc776712015-02-17 20:18:47 -0800336 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700337 // Update battery life logging for flashlight
338 Mutex::Autolock al(mTorchClientMapMutex);
339 auto iter = mTorchUidMap.find(cameraId);
340 if (iter != mTorchUidMap.end()) {
341 int oldUid = iter->second.second;
342 int newUid = iter->second.first;
343 BatteryNotifier& notifier(BatteryNotifier::getInstance());
344 if (oldUid != newUid) {
345 // If the UID has changed, log the status and update current UID in mTorchUidMap
346 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
347 notifier.noteFlashlightOff(cameraId, oldUid);
348 }
349 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
350 notifier.noteFlashlightOn(cameraId, newUid);
351 }
352 iter->second.second = newUid;
353 } else {
354 // If the UID has not changed, log the status
355 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
356 notifier.noteFlashlightOn(cameraId, oldUid);
357 } else {
358 notifier.noteFlashlightOff(cameraId, oldUid);
359 }
360 }
361 }
362 }
363
364 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800365 Mutex::Autolock lock(mStatusListenerLock);
366 for (auto& i : mListenerList) {
367 i->onTorchStatusChanged(newStatus, String16{cameraId});
368 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800369 }
370}
371
372
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373int32_t CameraService::getNumberOfCameras() {
374 return mNumberOfCameras;
375}
376
377status_t CameraService::getCameraInfo(int cameraId,
378 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700379 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700380 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700381 }
382
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
384 return BAD_VALUE;
385 }
386
Iliyan Malchev8951a972011-04-14 16:55:59 -0700387 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700388 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800389 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700390 cameraInfo->facing = info.facing;
391 cameraInfo->orientation = info.orientation;
392 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393}
394
Ruben Brunkcc776712015-02-17 20:18:47 -0800395int CameraService::cameraIdToInt(const String8& cameraId) {
396 errno = 0;
397 size_t pos = 0;
398 int ret = stoi(std::string{cameraId.string()}, &pos);
399 if (errno != 0 || pos != cameraId.size()) {
400 return -1;
401 }
402 return ret;
403}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700404
405status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
406 status_t ret = OK;
407 struct CameraInfo info;
408 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
409 return ret;
410 }
411
412 CameraMetadata shimInfo;
413 int32_t orientation = static_cast<int32_t>(info.orientation);
414 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
415 return ret;
416 }
417
418 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
419 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
420 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
421 return ret;
422 }
423
Igor Murashkin65d14b92014-06-17 12:03:20 -0700424 CameraParameters shimParams;
425 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
426 // Error logged by callee
427 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700428 }
429
430 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700431 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700432 Vector<int32_t> formats;
433 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700434 {
435 shimParams.getSupportedPreviewSizes(/*out*/sizes);
436 shimParams.getSupportedPreviewFormats(/*out*/formats);
437 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700438 }
439
440 // Always include IMPLEMENTATION_DEFINED
441 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
442
443 const size_t INTS_PER_CONFIG = 4;
444
445 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700446 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
447
448 Vector<int32_t> streamConfigs;
449 streamConfigs.setCapacity(streamConfigSize);
450
Ruben Brunkb2119af2014-05-09 19:57:56 -0700451 for (size_t i = 0; i < formats.size(); ++i) {
452 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700453 streamConfigs.add(formats[i]);
454 streamConfigs.add(sizes[j].width);
455 streamConfigs.add(sizes[j].height);
456 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700457 }
458 }
459
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700460 for (size_t i = 0; i < jpegSizes.size(); ++i) {
461 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
462 streamConfigs.add(jpegSizes[i].width);
463 streamConfigs.add(jpegSizes[i].height);
464 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
465 }
466
Ruben Brunkb2119af2014-05-09 19:57:56 -0700467 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700468 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700469 return ret;
470 }
471
472 int64_t fakeMinFrames[0];
473 // TODO: Fixme, don't fake min frame durations.
474 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
475 fakeMinFrames, 0)) != OK) {
476 return ret;
477 }
478
479 int64_t fakeStalls[0];
480 // TODO: Fixme, don't fake stall durations.
481 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
482 fakeStalls, 0)) != OK) {
483 return ret;
484 }
485
486 *cameraInfo = shimInfo;
487 return OK;
488}
489
Zhijun He2b59be82013-09-25 10:14:30 -0700490status_t CameraService::getCameraCharacteristics(int cameraId,
491 CameraMetadata* cameraInfo) {
492 if (!cameraInfo) {
493 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
494 return BAD_VALUE;
495 }
496
497 if (!mModule) {
498 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
499 return -ENODEV;
500 }
501
Zhijun He2b59be82013-09-25 10:14:30 -0700502 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
503 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
504 return BAD_VALUE;
505 }
506
507 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700508 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800509 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700510 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
511 /**
512 * Backwards compatibility mode for old HALs:
513 * - Convert CameraInfo into static CameraMetadata properties.
514 * - Retrieve cached CameraParameters for this camera. If none exist,
515 * attempt to open CameraClient and retrieve the CameraParameters.
516 * - Convert cached CameraParameters into static CameraMetadata
517 * properties.
518 */
519 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700520
Ruben Brunkb2119af2014-05-09 19:57:56 -0700521 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
522 return ret;
523 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700524
Ruben Brunkb2119af2014-05-09 19:57:56 -0700525 } else {
526 /**
527 * Normal HAL 2.1+ codepath.
528 */
529 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800530 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700531 *cameraInfo = info.static_camera_characteristics;
532 }
Zhijun He2b59be82013-09-25 10:14:30 -0700533
534 return ret;
535}
536
Ruben Brunkcc776712015-02-17 20:18:47 -0800537int CameraService::getCallingPid() {
538 return IPCThreadState::self()->getCallingPid();
539}
540
541int CameraService::getCallingUid() {
542 return IPCThreadState::self()->getCallingUid();
543}
544
545String8 CameraService::getFormattedCurrentTime() {
546 time_t now = time(nullptr);
547 char formattedTime[64];
548 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
549 return String8(formattedTime);
550}
551
552int CameraService::getCameraPriorityFromProcState(int procState) {
553 // Find the priority for the camera usage based on the process state. Higher priority clients
554 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700555 if (procState < 0) {
556 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
557 procState);
558 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800559 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700560 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800561}
562
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800563status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
564 if (!mModule) {
565 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
566 return -ENODEV;
567 }
568
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800569 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
570 return OK;
571}
572
Igor Murashkin634a5152013-02-20 17:15:11 -0800573int CameraService::getDeviceVersion(int cameraId, int* facing) {
574 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800575 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800576 return -1;
577 }
578
579 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800580 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800581 deviceVersion = info.device_version;
582 } else {
583 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
584 }
585
586 if (facing) {
587 *facing = info.facing;
588 }
589
590 return deviceVersion;
591}
592
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700593status_t CameraService::filterGetInfoErrorCode(status_t err) {
594 switch(err) {
595 case NO_ERROR:
596 case -EINVAL:
597 return err;
598 default:
599 break;
600 }
601 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800602}
603
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800604bool CameraService::setUpVendorTags() {
605 vendor_tag_ops_t vOps = vendor_tag_ops_t();
606
607 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800608 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800609 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
610 return false;
611 }
612
613 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800614 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800615 ATRACE_END();
616
617 // Ensure all vendor operations are present
618 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
619 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
620 vOps.get_tag_type == NULL) {
621 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
622 , __FUNCTION__);
623 return false;
624 }
625
626 // Read all vendor tag definitions into a descriptor
627 sp<VendorTagDescriptor> desc;
628 status_t res;
629 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
630 != OK) {
631 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
632 "received error %s (%d). Camera clients will not be able to use"
633 "vendor tags", __FUNCTION__, strerror(res), res);
634 return false;
635 }
636
637 // Set the global descriptor to use with camera metadata
638 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
639 return true;
640}
641
Ruben Brunkcc776712015-02-17 20:18:47 -0800642status_t CameraService::makeClient(const sp<CameraService>& cameraService,
643 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
644 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
645 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
646 /*out*/sp<BasicClient>* client) {
647
648 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
649 int id = cameraIdToInt(cameraId);
650 if (id == -1) {
651 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
652 cameraId.string());
653 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700654 }
655
Ruben Brunkcc776712015-02-17 20:18:47 -0800656 if (halVersion < 0 || halVersion == deviceVersion) {
657 // Default path: HAL version is unspecified by caller, create CameraClient
658 // based on device version reported by the HAL.
659 switch(deviceVersion) {
660 case CAMERA_DEVICE_API_VERSION_1_0:
661 if (effectiveApiLevel == API_1) { // Camera1 API route
662 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
663 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
664 clientPid, clientUid, getpid(), legacyMode);
665 } else { // Camera2 API route
666 ALOGW("Camera using old HAL version: %d", deviceVersion);
667 return -EOPNOTSUPP;
668 }
669 break;
670 case CAMERA_DEVICE_API_VERSION_2_0:
671 case CAMERA_DEVICE_API_VERSION_2_1:
672 case CAMERA_DEVICE_API_VERSION_3_0:
673 case CAMERA_DEVICE_API_VERSION_3_1:
674 case CAMERA_DEVICE_API_VERSION_3_2:
675 case CAMERA_DEVICE_API_VERSION_3_3:
676 if (effectiveApiLevel == API_1) { // Camera1 API route
677 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
678 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
679 clientPid, clientUid, servicePid, legacyMode);
680 } else { // Camera2 API route
681 sp<ICameraDeviceCallbacks> tmp =
682 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
683 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
684 facing, clientPid, clientUid, servicePid);
685 }
686 break;
687 default:
688 // Should not be reachable
689 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
690 return INVALID_OPERATION;
691 }
692 } else {
693 // A particular HAL version is requested by caller. Create CameraClient
694 // based on the requested HAL version.
695 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
696 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
697 // Only support higher HAL version device opened as HAL1.0 device.
698 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
699 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
700 clientPid, clientUid, servicePid, legacyMode);
701 } else {
702 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
703 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
704 " opened as HAL %x device", halVersion, deviceVersion,
705 CAMERA_DEVICE_API_VERSION_1_0);
706 return INVALID_OPERATION;
707 }
708 }
709 return NO_ERROR;
710}
711
Ruben Brunk6267b532015-04-30 17:44:07 -0700712String8 CameraService::toString(std::set<userid_t> intSet) {
713 String8 s("");
714 bool first = true;
715 for (userid_t i : intSet) {
716 if (first) {
717 s.appendFormat("%d", i);
718 first = false;
719 } else {
720 s.appendFormat(", %d", i);
721 }
722 }
723 return s;
724}
725
Ruben Brunkcc776712015-02-17 20:18:47 -0800726status_t CameraService::initializeShimMetadata(int cameraId) {
727 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700728
729 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800730 String8 id = String8::format("%d", cameraId);
731 status_t ret = NO_ERROR;
732 sp<Client> tmp = nullptr;
733 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
734 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
735 false, true, tmp)) != NO_ERROR) {
736 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
737 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700738 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800739 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700740}
741
Igor Murashkin65d14b92014-06-17 12:03:20 -0700742status_t CameraService::getLegacyParametersLazy(int cameraId,
743 /*out*/
744 CameraParameters* parameters) {
745
746 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
747
748 status_t ret = 0;
749
750 if (parameters == NULL) {
751 ALOGE("%s: parameters must not be null", __FUNCTION__);
752 return BAD_VALUE;
753 }
754
Ruben Brunkcc776712015-02-17 20:18:47 -0800755 String8 id = String8::format("%d", cameraId);
756
757 // Check if we already have parameters
758 {
759 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700760 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800761 auto cameraState = getCameraState(id);
762 if (cameraState == nullptr) {
763 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
764 return BAD_VALUE;
765 }
766 CameraParameters p = cameraState->getShimParams();
767 if (!p.isEmpty()) {
768 *parameters = p;
769 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700770 }
771 }
772
Ruben Brunkcc776712015-02-17 20:18:47 -0800773 int64_t token = IPCThreadState::self()->clearCallingIdentity();
774 ret = initializeShimMetadata(cameraId);
775 IPCThreadState::self()->restoreCallingIdentity(token);
776 if (ret != NO_ERROR) {
777 // Error already logged by callee
778 return ret;
779 }
780
781 // Check for parameters again
782 {
783 // Scope for service lock
784 Mutex::Autolock lock(mServiceLock);
785 auto cameraState = getCameraState(id);
786 if (cameraState == nullptr) {
787 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
788 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700789 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800790 CameraParameters p = cameraState->getShimParams();
791 if (!p.isEmpty()) {
792 *parameters = p;
793 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700794 }
795 }
796
Ruben Brunkcc776712015-02-17 20:18:47 -0800797 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
798 __FUNCTION__);
799 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700800}
801
Ruben Brunk36597b22015-03-20 22:15:57 -0700802status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
803 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800804
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500806
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800807 if (clientUid == USE_CALLING_UID) {
808 clientUid = getCallingUid();
809 } else {
810 // We only trust our own process to forward client UIDs
811 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700812 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
813 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700814 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800815 }
816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817
Iliyan Malchev8951a972011-04-14 16:55:59 -0700818 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800819 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
820 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700821 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700822 }
823
Ruben Brunkcc776712015-02-17 20:18:47 -0800824 if (getCameraState(cameraId) == nullptr) {
825 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
826 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700827 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 }
829
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800831 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800832 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700833 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800834 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
835 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800836 if (strcmp(value, "1") == 0) {
837 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800838 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
839 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700840 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800841 }
842
Ruben Brunka8ca9152015-04-07 14:23:40 -0700843 // Only allow clients who are being used by the current foreground device user, unless calling
844 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700845 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
846 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
847 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
848 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700849 return PERMISSION_DENIED;
850 }
851
Ruben Brunkcc776712015-02-17 20:18:47 -0800852 return checkIfDeviceIsUsable(cameraId);
853}
854
855status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
856 auto cameraState = getCameraState(cameraId);
857 int callingPid = getCallingPid();
858 if (cameraState == nullptr) {
859 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
860 cameraId.string());
861 return -ENODEV;
862 }
863
864 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700865 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800866 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
867 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700868 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700869 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800870 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
871 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700872 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700873 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700874
Ruben Brunkcc776712015-02-17 20:18:47 -0800875 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800876}
877
Ruben Brunkcc776712015-02-17 20:18:47 -0800878void CameraService::finishConnectLocked(const sp<BasicClient>& client,
879 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800880
Ruben Brunkcc776712015-02-17 20:18:47 -0800881 // Make a descriptor for the incoming client
882 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
883 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
884
885 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
886 String8(client->getPackageName()));
887
888 if (evicted.size() > 0) {
889 // This should never happen - clients should already have been removed in disconnect
890 for (auto& i : evicted) {
891 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
892 __FUNCTION__, i->getKey().string());
893 }
894
895 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
896 __FUNCTION__);
897 }
898}
899
900status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
901 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
902 /*out*/
903 sp<BasicClient>* client,
904 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
905
906 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700907 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800908 DescriptorPtr clientDescriptor;
909 {
910 if (effectiveApiLevel == API_1) {
911 // If we are using API1, any existing client for this camera ID with the same remote
912 // should be returned rather than evicted to allow MediaRecorder to work properly.
913
914 auto current = mActiveClientManager.get(cameraId);
915 if (current != nullptr) {
916 auto clientSp = current->getValue();
917 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700918 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
919 ALOGW("CameraService connect called from same client, but with a different"
920 " API level, evicting prior client...");
921 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800922 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700923 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800924 *client = clientSp;
925 return NO_ERROR;
926 }
927 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800928 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800929 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800930
Ruben Brunkcc776712015-02-17 20:18:47 -0800931 // Return error if the device was unplugged or removed by the HAL for some reason
932 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
933 return ret;
934 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800935
Ruben Brunkcc776712015-02-17 20:18:47 -0800936 // Get current active client PIDs
937 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
938 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800939
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700940 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
941 // address of PROCESS_STATE_NONEXISTENT as a reference argument
942 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
943 // not have an out-of-class definition.
944 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800945
Ruben Brunkcc776712015-02-17 20:18:47 -0800946 // Get priorites of all active PIDs
947 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
948 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700949
Ruben Brunkcc776712015-02-17 20:18:47 -0800950 // Update all active clients' priorities
951 std::map<int,int> pidToPriorityMap;
952 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
953 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
954 }
955 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800956
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 // Get state for the given cameraId
958 auto state = getCameraState(cameraId);
959 if (state == nullptr) {
960 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
961 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700962 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -0700963 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800964
965 // Make descriptor for incoming client
966 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
967 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
968 state->getConflicting(),
969 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
970
971 // Find clients that would be evicted
972 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
973
974 // If the incoming client was 'evicted,' higher priority clients have the camera in the
975 // background, so we cannot do evictions
976 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
977 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
978 " priority).", clientPid);
979
980 sp<BasicClient> clientSp = clientDescriptor->getValue();
981 String8 curTime = getFormattedCurrentTime();
982 auto incompatibleClients =
983 mActiveClientManager.getIncompatibleClients(clientDescriptor);
984
985 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -0700986 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800987 cameraId.string(), packageName.string(), clientPid,
988 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
989
990 for (auto& i : incompatibleClients) {
991 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
992 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
993 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
994 i->getPriority());
995 }
996
997 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -0700998 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800999 mEventLog.add(msg);
1000
1001 return -EBUSY;
1002 }
1003
1004 for (auto& i : evicted) {
1005 sp<BasicClient> clientSp = i->getValue();
1006 if (clientSp.get() == nullptr) {
1007 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1008
1009 // TODO: Remove this
1010 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1011 __FUNCTION__);
1012 mActiveClientManager.remove(i);
1013 continue;
1014 }
1015
1016 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1017 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001018 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001019
Ruben Brunkcc776712015-02-17 20:18:47 -08001020 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001021 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1022 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1023 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001024 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1025 i->getOwnerId(), i->getPriority(), cameraId.string(),
1026 packageName.string(), clientPid,
1027 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1028
1029 // Notify the client of disconnection
1030 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1031 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001032 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001033 }
1034
Ruben Brunkcc776712015-02-17 20:18:47 -08001035 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1036 // other clients from connecting in mServiceLockWrapper if held
1037 mServiceLock.unlock();
1038
1039 // Clear caller identity temporarily so client disconnect PID checks work correctly
1040 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1041
1042 // Destroy evicted clients
1043 for (auto& i : evictedClients) {
1044 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001045 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001046 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001047
1048 IPCThreadState::self()->restoreCallingIdentity(token);
1049
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001050 for (const auto& i : evictedClients) {
1051 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1052 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1053 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1054 if (ret == TIMED_OUT) {
1055 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1056 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1057 mActiveClientManager.toString().string());
1058 return -EBUSY;
1059 }
1060 if (ret != NO_ERROR) {
1061 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1062 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1063 ret, mActiveClientManager.toString().string());
1064 return ret;
1065 }
1066 }
1067
1068 evictedClients.clear();
1069
Ruben Brunkcc776712015-02-17 20:18:47 -08001070 // Once clients have been disconnected, relock
1071 mServiceLock.lock();
1072
1073 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1074 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1075 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001076 }
1077
Ruben Brunkcc776712015-02-17 20:18:47 -08001078 *partial = clientDescriptor;
1079 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001080}
1081
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001082status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001083 const sp<ICameraClient>& cameraClient,
1084 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001085 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001086 int clientUid,
1087 /*out*/
1088 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001089
Ruben Brunkcc776712015-02-17 20:18:47 -08001090 status_t ret = NO_ERROR;
1091 String8 id = String8::format("%d", cameraId);
1092 sp<Client> client = nullptr;
1093 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001094 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001095
Ruben Brunkcc776712015-02-17 20:18:47 -08001096 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001097 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001098 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001099 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 }
1101
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001102 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001103 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104}
1105
Zhijun Heb10cdad2014-06-16 16:38:35 -07001106status_t CameraService::connectLegacy(
1107 const sp<ICameraClient>& cameraClient,
1108 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001109 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001110 int clientUid,
1111 /*out*/
1112 sp<ICamera>& device) {
1113
Ruben Brunka8ca9152015-04-07 14:23:40 -07001114 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001115 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001116 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001117 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001118 /*
1119 * Either the HAL version is unspecified in which case this just creates
1120 * a camera client selected by the latest device version, or
1121 * it's a particular version in which case the HAL must supported
1122 * the open_legacy call
1123 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001124 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001125 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001126 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001127 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001128 return INVALID_OPERATION;
1129 }
1130
Ruben Brunkcc776712015-02-17 20:18:47 -08001131 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001133 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001135
Ruben Brunkcc776712015-02-17 20:18:47 -08001136 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001137 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001138 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001139 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001140 }
1141
Zhijun Heb10cdad2014-06-16 16:38:35 -07001142 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001144}
1145
Ruben Brunkcc776712015-02-17 20:18:47 -08001146status_t CameraService::connectDevice(
1147 const sp<ICameraDeviceCallbacks>& cameraCb,
1148 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001149 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 int clientUid,
1151 /*out*/
1152 sp<ICameraDeviceUser>& device) {
1153
1154 status_t ret = NO_ERROR;
1155 String8 id = String8::format("%d", cameraId);
1156 sp<CameraDeviceClient> client = nullptr;
1157 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001158 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001159 /*out*/client);
1160
1161 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001162 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001163 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001164 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001165 }
1166
Ruben Brunkcc776712015-02-17 20:18:47 -08001167 device = client;
1168 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001169}
1170
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001171status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1172 const sp<IBinder>& clientBinder) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001173 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001174 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001175 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001176 }
1177
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001178 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001179 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001180
1181 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 auto state = getCameraState(id);
1183 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001184 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001185 return -EINVAL;
1186 }
1187
1188 ICameraServiceListener::Status cameraStatus = state->getStatus();
1189 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1190 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001191 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001192 return -EINVAL;
1193 }
1194
1195 {
1196 Mutex::Autolock al(mTorchStatusMutex);
1197 ICameraServiceListener::TorchStatus status;
1198 status_t res = getTorchStatusLocked(id, &status);
1199 if (res) {
1200 ALOGE("%s: getting current torch status failed for camera %s",
1201 __FUNCTION__, id.string());
1202 return -EINVAL;
1203 }
1204
1205 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001206 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001207 ALOGE("%s: torch mode of camera %s is not available because "
1208 "camera is in use", __FUNCTION__, id.string());
1209 return -EBUSY;
1210 } else {
1211 ALOGE("%s: torch mode of camera %s is not available due to "
1212 "insufficient resources", __FUNCTION__, id.string());
1213 return -EUSERS;
1214 }
1215 }
1216 }
1217
Ruben Brunk99e69712015-05-26 17:25:07 -07001218 {
1219 // Update UID map - this is used in the torch status changed callbacks, so must be done
1220 // before setTorchMode
1221 Mutex::Autolock al(mTorchClientMapMutex);
1222 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1223 mTorchUidMap[id].first = uid;
1224 mTorchUidMap[id].second = uid;
1225 } else {
1226 // Set the pending UID
1227 mTorchUidMap[id].first = uid;
1228 }
1229 }
1230
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001231 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001232
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001233 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001234 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1235 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001236 return res;
1237 }
1238
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001239 {
1240 // update the link to client's death
1241 Mutex::Autolock al(mTorchClientMapMutex);
1242 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001243 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001244 if (enabled) {
1245 if (index == NAME_NOT_FOUND) {
1246 mTorchClientMap.add(id, clientBinder);
1247 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001248 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001249 mTorchClientMap.replaceValueAt(index, clientBinder);
1250 }
1251 clientBinder->linkToDeath(this);
1252 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001253 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001254 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001255 }
1256
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001257 return OK;
1258}
1259
Ruben Brunk6267b532015-04-30 17:44:07 -07001260void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001261 switch(eventId) {
1262 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001263 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001264 break;
1265 }
1266 case ICameraService::NO_EVENT:
1267 default: {
1268 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1269 eventId);
1270 break;
1271 }
1272 }
1273}
1274
Ruben Brunk99e69712015-05-26 17:25:07 -07001275status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001276 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001277
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001278 if (listener == 0) {
1279 ALOGE("%s: Listener must not be null", __FUNCTION__);
1280 return BAD_VALUE;
1281 }
1282
Igor Murashkinbfc99152013-02-27 12:55:20 -08001283 Mutex::Autolock lock(mServiceLock);
1284
Ruben Brunkcc776712015-02-17 20:18:47 -08001285 {
1286 Mutex::Autolock lock(mStatusListenerLock);
1287 for (auto& it : mListenerList) {
1288 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1289 ALOGW("%s: Tried to add listener %p which was already subscribed",
1290 __FUNCTION__, listener.get());
1291 return ALREADY_EXISTS;
1292 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001293 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001294
1295 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001296 }
1297
Igor Murashkinbfc99152013-02-27 12:55:20 -08001298
Igor Murashkincba2c162013-03-20 15:56:31 -07001299 /* Immediately signal current status to this listener only */
1300 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001301 Mutex::Autolock lock(mCameraStatesLock);
1302 for (auto& i : mCameraStates) {
1303 // TODO: Update binder to use String16 for camera IDs and remove;
1304 int id = cameraIdToInt(i.first);
1305 if (id == -1) continue;
1306
1307 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001308 }
1309 }
1310
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001311 /* Immediately signal current torch status to this listener only */
1312 {
1313 Mutex::Autolock al(mTorchStatusMutex);
1314 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001315 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1316 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001317 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001318 }
1319
Igor Murashkinbfc99152013-02-27 12:55:20 -08001320 return OK;
1321}
Ruben Brunkcc776712015-02-17 20:18:47 -08001322
1323status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001324 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1325
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001326 if (listener == 0) {
1327 ALOGE("%s: Listener must not be null", __FUNCTION__);
1328 return BAD_VALUE;
1329 }
1330
Igor Murashkinbfc99152013-02-27 12:55:20 -08001331 Mutex::Autolock lock(mServiceLock);
1332
Ruben Brunkcc776712015-02-17 20:18:47 -08001333 {
1334 Mutex::Autolock lock(mStatusListenerLock);
1335 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1336 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1337 mListenerList.erase(it);
1338 return OK;
1339 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001340 }
1341 }
1342
1343 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1344 __FUNCTION__, listener.get());
1345
1346 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001347}
1348
Ruben Brunkcc776712015-02-17 20:18:47 -08001349status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001350 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1351
1352 if (parameters == NULL) {
1353 ALOGE("%s: parameters must not be null", __FUNCTION__);
1354 return BAD_VALUE;
1355 }
1356
1357 status_t ret = 0;
1358
1359 CameraParameters shimParams;
1360 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1361 // Error logged by caller
1362 return ret;
1363 }
1364
1365 String8 shimParamsString8 = shimParams.flatten();
1366 String16 shimParamsString16 = String16(shimParamsString8);
1367
1368 *parameters = shimParamsString16;
1369
1370 return OK;
1371}
1372
1373status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1374 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1375
1376 switch (apiVersion) {
1377 case API_VERSION_1:
1378 case API_VERSION_2:
1379 break;
1380 default:
1381 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1382 return BAD_VALUE;
1383 }
1384
1385 int facing = -1;
1386 int deviceVersion = getDeviceVersion(cameraId, &facing);
1387
1388 switch(deviceVersion) {
1389 case CAMERA_DEVICE_API_VERSION_1_0:
1390 case CAMERA_DEVICE_API_VERSION_2_0:
1391 case CAMERA_DEVICE_API_VERSION_2_1:
1392 case CAMERA_DEVICE_API_VERSION_3_0:
1393 case CAMERA_DEVICE_API_VERSION_3_1:
1394 if (apiVersion == API_VERSION_2) {
1395 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1396 __FUNCTION__, cameraId);
1397 return -EOPNOTSUPP;
1398 } else { // if (apiVersion == API_VERSION_1) {
1399 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1400 __FUNCTION__, cameraId);
1401 return OK;
1402 }
1403 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001404 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001405 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1406 __FUNCTION__, cameraId);
1407 return OK;
1408 case -1:
1409 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1410 return BAD_VALUE;
1411 default:
1412 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1413 return INVALID_OPERATION;
1414 }
1415
1416 return OK;
1417}
1418
Ruben Brunkcc776712015-02-17 20:18:47 -08001419void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001420 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001421 for (auto& i : mActiveClientManager.getAll()) {
1422 auto clientSp = i->getValue();
1423 if (clientSp.get() == client) {
1424 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001425 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001426 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001427}
1428
Ruben Brunkcc776712015-02-17 20:18:47 -08001429bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1430 const int callingPid = getCallingPid();
1431 const int servicePid = getpid();
1432 bool ret = false;
1433 {
1434 // Acquire mServiceLock and prevent other clients from connecting
1435 std::unique_ptr<AutoConditionLock> lock =
1436 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001437
Igor Murashkin634a5152013-02-20 17:15:11 -08001438
Ruben Brunkcc776712015-02-17 20:18:47 -08001439 std::vector<sp<BasicClient>> evicted;
1440 for (auto& i : mActiveClientManager.getAll()) {
1441 auto clientSp = i->getValue();
1442 if (clientSp.get() == nullptr) {
1443 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1444 mActiveClientManager.remove(i);
1445 continue;
1446 }
1447 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1448 callingPid == clientSp->getClientPid())) {
1449 mActiveClientManager.remove(i);
1450 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001451
Ruben Brunkcc776712015-02-17 20:18:47 -08001452 // Notify the client of disconnection
1453 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1454 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001455 }
1456 }
1457
Ruben Brunkcc776712015-02-17 20:18:47 -08001458 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1459 // other clients from connecting in mServiceLockWrapper if held
1460 mServiceLock.unlock();
1461
Ruben Brunk36597b22015-03-20 22:15:57 -07001462 // Do not clear caller identity, remote caller should be client proccess
1463
Ruben Brunkcc776712015-02-17 20:18:47 -08001464 for (auto& i : evicted) {
1465 if (i.get() != nullptr) {
1466 i->disconnect();
1467 ret = true;
1468 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001469 }
1470
Ruben Brunkcc776712015-02-17 20:18:47 -08001471 // Reacquire mServiceLock
1472 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001473
Ruben Brunkcc776712015-02-17 20:18:47 -08001474 } // lock is destroyed, allow further connect calls
1475
1476 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001477}
1478
Igor Murashkinecf17e82012-10-02 16:05:11 -07001479
Ruben Brunkcc776712015-02-17 20:18:47 -08001480std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1481 const String8& cameraId) const {
1482 std::shared_ptr<CameraState> state;
1483 {
1484 Mutex::Autolock lock(mCameraStatesLock);
1485 auto iter = mCameraStates.find(cameraId);
1486 if (iter != mCameraStates.end()) {
1487 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 }
1489 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001490 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491}
1492
Ruben Brunkcc776712015-02-17 20:18:47 -08001493sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1494 // Remove from active clients list
1495 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1496 if (clientDescriptorPtr == nullptr) {
1497 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1498 cameraId.string());
1499 return sp<BasicClient>{nullptr};
1500 }
1501
1502 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001503}
1504
Ruben Brunk6267b532015-04-30 17:44:07 -07001505void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001506 // Acquire mServiceLock and prevent other clients from connecting
1507 std::unique_ptr<AutoConditionLock> lock =
1508 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1509
Ruben Brunk6267b532015-04-30 17:44:07 -07001510 std::set<userid_t> newAllowedUsers;
1511 for (size_t i = 0; i < length; i++) {
1512 if (newUserId[i] < 0) {
1513 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1514 __FUNCTION__, newUserId[i]);
1515 return;
1516 }
1517 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001518 }
1519
Ruben Brunka8ca9152015-04-07 14:23:40 -07001520
Ruben Brunk6267b532015-04-30 17:44:07 -07001521 if (newAllowedUsers == mAllowedUsers) {
1522 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1523 return;
1524 }
1525
1526 logUserSwitch(mAllowedUsers, newAllowedUsers);
1527
1528 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001529
1530 // Current user has switched, evict all current clients.
1531 std::vector<sp<BasicClient>> evicted;
1532 for (auto& i : mActiveClientManager.getAll()) {
1533 auto clientSp = i->getValue();
1534
1535 if (clientSp.get() == nullptr) {
1536 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1537 continue;
1538 }
1539
Ruben Brunk6267b532015-04-30 17:44:07 -07001540 // Don't evict clients that are still allowed.
1541 uid_t clientUid = clientSp->getClientUid();
1542 userid_t clientUserId = multiuser_get_user_id(clientUid);
1543 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1544 continue;
1545 }
1546
Ruben Brunk36597b22015-03-20 22:15:57 -07001547 evicted.push_back(clientSp);
1548
1549 String8 curTime = getFormattedCurrentTime();
1550
1551 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1552 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001553
Ruben Brunk36597b22015-03-20 22:15:57 -07001554 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001555 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001556 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001557 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1558 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001559
1560 }
1561
1562 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1563 // blocking other clients from connecting in mServiceLockWrapper if held.
1564 mServiceLock.unlock();
1565
1566 // Clear caller identity temporarily so client disconnect PID checks work correctly
1567 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1568
1569 for (auto& i : evicted) {
1570 i->disconnect();
1571 }
1572
1573 IPCThreadState::self()->restoreCallingIdentity(token);
1574
1575 // Reacquire mServiceLock
1576 mServiceLock.lock();
1577}
Ruben Brunkcc776712015-02-17 20:18:47 -08001578
Ruben Brunka8ca9152015-04-07 14:23:40 -07001579void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001580 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001581 Mutex::Autolock l(mLogLock);
1582 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583}
1584
Ruben Brunka8ca9152015-04-07 14:23:40 -07001585void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001586 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001587 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001588 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001589 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001590}
1591
1592void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001593 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001594 // Log the clients evicted
1595 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001596 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001597}
1598
1599void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001600 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001601 // Log the client rejected
1602 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001603 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001604}
1605
Ruben Brunk6267b532015-04-30 17:44:07 -07001606void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1607 const std::set<userid_t>& newUserIds) {
1608 String8 newUsers = toString(newUserIds);
1609 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001610 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001611 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1612 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001613}
1614
1615void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1616 // Log the device removal
1617 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1618}
1619
1620void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1621 // Log the device removal
1622 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1623}
1624
1625void CameraService::logClientDied(int clientPid, const char* reason) {
1626 // Log the device removal
1627 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001628}
1629
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001630void CameraService::logServiceError(const char* msg, int errorCode) {
1631 String8 curTime = getFormattedCurrentTime();
1632 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1633}
1634
Ruben Brunk36597b22015-03-20 22:15:57 -07001635status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1636 uint32_t flags) {
1637
1638 const int pid = getCallingPid();
1639 const int selfPid = getpid();
1640
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 // Permission checks
1642 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001643 case BnCameraService::CONNECT:
1644 case BnCameraService::CONNECT_DEVICE:
1645 case BnCameraService::CONNECT_LEGACY: {
1646 if (pid != selfPid) {
1647 // we're called from a different process, do the real check
1648 if (!checkCallingPermission(
1649 String16("android.permission.CAMERA"))) {
1650 const int uid = getCallingUid();
1651 ALOGE("Permission Denial: "
1652 "can't use the camera pid=%d, uid=%d", pid, uid);
1653 return PERMISSION_DENIED;
1654 }
1655 }
1656 break;
1657 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001658 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1659 if (pid != selfPid) {
1660 // Ensure we're being called by system_server, or similar process with
1661 // permissions to notify the camera service about system events
1662 if (!checkCallingPermission(
1663 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1664 const int uid = getCallingUid();
1665 ALOGE("Permission Denial: cannot send updates to camera service about system"
1666 " events from pid=%d, uid=%d", pid, uid);
1667 return PERMISSION_DENIED;
1668 }
1669 }
1670 break;
1671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672 }
1673
1674 return BnCameraService::onTransact(code, data, reply, flags);
1675}
1676
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677// We share the media players for shutter and recording sound for all clients.
1678// A reference count is kept to determine when we will actually release the
1679// media players.
1680
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001681MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001683 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001684 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 mp->prepare();
1686 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001687 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688 return NULL;
1689 }
1690 return mp;
1691}
1692
1693void CameraService::loadSound() {
1694 Mutex::Autolock lock(mSoundLock);
1695 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1696 if (mSoundRef++) return;
1697
1698 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1699 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1700}
1701
1702void CameraService::releaseSound() {
1703 Mutex::Autolock lock(mSoundLock);
1704 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1705 if (--mSoundRef) return;
1706
1707 for (int i = 0; i < NUM_SOUNDS; i++) {
1708 if (mSoundPlayer[i] != 0) {
1709 mSoundPlayer[i]->disconnect();
1710 mSoundPlayer[i].clear();
1711 }
1712 }
1713}
1714
1715void CameraService::playSound(sound_kind kind) {
1716 LOG1("playSound(%d)", kind);
1717 Mutex::Autolock lock(mSoundLock);
1718 sp<MediaPlayer> player = mSoundPlayer[kind];
1719 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001720 player->seekTo(0);
1721 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722 }
1723}
1724
1725// ----------------------------------------------------------------------------
1726
1727CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001728 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001729 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001730 int cameraId, int cameraFacing,
1731 int clientPid, uid_t clientUid,
1732 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001733 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001734 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001735 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001736 cameraId, cameraFacing,
1737 clientPid, clientUid,
1738 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001739{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001741 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001743 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001746
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001747 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748}
1749
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750// tear down the client
1751CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001752 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001753 mDestructionStarted = true;
1754
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001755 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001756 // unconditionally disconnect. function is idempotent
1757 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758}
1759
Igor Murashkin634a5152013-02-20 17:15:11 -08001760CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001761 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001762 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001763 int cameraId, int cameraFacing,
1764 int clientPid, uid_t clientUid,
1765 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001766 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001767{
1768 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001769 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001770 mCameraId = cameraId;
1771 mCameraFacing = cameraFacing;
1772 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001773 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001774 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001775 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001776 mDestructionStarted = false;
1777}
1778
1779CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001780 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001781 mDestructionStarted = true;
1782}
1783
1784void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001785 if (mDisconnected) {
1786 ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1787 mCameraId);
1788 return;
1789 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001790 mDisconnected = true;;
1791
1792 mCameraService->removeByClient(this);
1793 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001794 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001795
1796 sp<IBinder> remote = getRemote();
1797 if (remote != nullptr) {
1798 remote->unlinkToDeath(mCameraService);
1799 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001800
1801 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001802 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1803
Igor Murashkincba2c162013-03-20 15:56:31 -07001804 // client shouldn't be able to call into us anymore
1805 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001806}
1807
Ruben Brunkcc776712015-02-17 20:18:47 -08001808String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001809 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001810}
1811
1812
1813int CameraService::BasicClient::getClientPid() const {
1814 return mClientPid;
1815}
1816
Ruben Brunk6267b532015-04-30 17:44:07 -07001817uid_t CameraService::BasicClient::getClientUid() const {
1818 return mClientUid;
1819}
1820
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001821bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1822 // Defaults to API2.
1823 return level == API_2;
1824}
1825
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001826status_t CameraService::BasicClient::startCameraOps() {
1827 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001828 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001829 mOpsCallback = new OpsCallback(this);
1830
Igor Murashkine6800ce2013-03-04 17:25:57 -08001831 {
1832 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001833 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001834 }
1835
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001836 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001837 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001838 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001839 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001840
Svetoslav28e8ef72015-05-11 19:21:31 -07001841 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001842 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001843 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001844 return PERMISSION_DENIED;
1845 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001846
Svetoslav28e8ef72015-05-11 19:21:31 -07001847 if (res == AppOpsManager::MODE_IGNORED) {
1848 ALOGI("Camera %d: Access for \"%s\" has been restricted",
1849 mCameraId, String8(mClientPackageName).string());
1850 return INVALID_OPERATION;
1851 }
1852
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001853 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001854
1855 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1856 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001857 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001858
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001859 return OK;
1860}
1861
1862status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001863 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001864 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001865 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001866 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001867 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001868 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001869
Ruben Brunkcc776712015-02-17 20:18:47 -08001870 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1871 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001872
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001874 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001875 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001876
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001877 // Notify flashlight that a camera device is closed.
1878 mCameraService->mFlashlight->deviceClosed(
1879 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001880 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001881 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001882 if (mOpsCallback != NULL) {
1883 mAppOpsManager.stopWatchingMode(mOpsCallback);
1884 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001885 mOpsCallback.clear();
1886
1887 return OK;
1888}
1889
1890void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1891 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001892 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001893
1894 if (op != AppOpsManager::OP_CAMERA) {
1895 ALOGW("Unexpected app ops notification received: %d", op);
1896 return;
1897 }
1898
1899 int32_t res;
1900 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001901 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001902 ALOGV("checkOp returns: %d, %s ", res,
1903 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1904 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1905 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1906 "UNKNOWN");
1907
1908 if (res != AppOpsManager::MODE_ALLOWED) {
1909 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1910 myName.string());
1911 // Reset the client PID to allow server-initiated disconnect,
1912 // and to prevent further calls by client.
1913 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07001914 CaptureResultExtras resultExtras; // a dummy result (invalid)
1915 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001916 disconnect();
1917 }
1918}
1919
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920// ----------------------------------------------------------------------------
1921
Ruben Brunkcc776712015-02-17 20:18:47 -08001922// Provide client strong pointer for callbacks.
1923sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
1924 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
1925 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
1926 if (clientDescriptor != nullptr) {
1927 return sp<Client>{
1928 static_cast<Client*>(clientDescriptor->getValue().get())};
1929 }
1930 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931}
1932
Jianing Weicb0652e2014-03-12 18:29:36 -07001933void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1934 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001935 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001936}
1937
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001938// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07001939void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001940 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08001941 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08001942}
1943
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001944bool CameraService::Client::canCastToApiClient(apiLevel level) const {
1945 return level == API_1;
1946}
1947
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001948CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1949 mClient(client) {
1950}
1951
1952void CameraService::Client::OpsCallback::opChanged(int32_t op,
1953 const String16& packageName) {
1954 sp<BasicClient> client = mClient.promote();
1955 if (client != NULL) {
1956 client->opChanged(op, packageName);
1957 }
1958}
1959
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08001961// CameraState
1962// ----------------------------------------------------------------------------
1963
1964CameraService::CameraState::CameraState(const String8& id, int cost,
1965 const std::set<String8>& conflicting) : mId(id),
1966 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
1967
1968CameraService::CameraState::~CameraState() {}
1969
1970ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
1971 Mutex::Autolock lock(mStatusLock);
1972 return mStatus;
1973}
1974
1975CameraParameters CameraService::CameraState::getShimParams() const {
1976 return mShimParams;
1977}
1978
1979void CameraService::CameraState::setShimParams(const CameraParameters& params) {
1980 mShimParams = params;
1981}
1982
1983int CameraService::CameraState::getCost() const {
1984 return mCost;
1985}
1986
1987std::set<String8> CameraService::CameraState::getConflicting() const {
1988 return mConflicting;
1989}
1990
1991String8 CameraService::CameraState::getId() const {
1992 return mId;
1993}
1994
1995// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07001996// ClientEventListener
1997// ----------------------------------------------------------------------------
1998
1999void CameraService::ClientEventListener::onClientAdded(
2000 const resource_policy::ClientDescriptor<String8,
2001 sp<CameraService::BasicClient>>& descriptor) {
2002 auto basicClient = descriptor.getValue();
2003 if (basicClient.get() != nullptr) {
2004 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2005 notifier.noteStartCamera(descriptor.getKey(),
2006 static_cast<int>(basicClient->getClientUid()));
2007 }
2008}
2009
2010void CameraService::ClientEventListener::onClientRemoved(
2011 const resource_policy::ClientDescriptor<String8,
2012 sp<CameraService::BasicClient>>& descriptor) {
2013 auto basicClient = descriptor.getValue();
2014 if (basicClient.get() != nullptr) {
2015 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2016 notifier.noteStopCamera(descriptor.getKey(),
2017 static_cast<int>(basicClient->getClientUid()));
2018 }
2019}
2020
2021
2022// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002023// CameraClientManager
2024// ----------------------------------------------------------------------------
2025
Ruben Brunk99e69712015-05-26 17:25:07 -07002026CameraService::CameraClientManager::CameraClientManager() {
2027 setListener(std::make_shared<ClientEventListener>());
2028}
2029
Ruben Brunkcc776712015-02-17 20:18:47 -08002030CameraService::CameraClientManager::~CameraClientManager() {}
2031
2032sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2033 const String8& id) const {
2034 auto descriptor = get(id);
2035 if (descriptor == nullptr) {
2036 return sp<BasicClient>{nullptr};
2037 }
2038 return descriptor->getValue();
2039}
2040
2041String8 CameraService::CameraClientManager::toString() const {
2042 auto all = getAll();
2043 String8 ret("[");
2044 bool hasAny = false;
2045 for (auto& i : all) {
2046 hasAny = true;
2047 String8 key = i->getKey();
2048 int32_t cost = i->getCost();
2049 int32_t pid = i->getOwnerId();
2050 int32_t priority = i->getPriority();
2051 auto conflicting = i->getConflicting();
2052 auto clientSp = i->getValue();
2053 String8 packageName;
Ruben Brunk6267b532015-04-30 17:44:07 -07002054 userid_t clientUserId;
Ruben Brunkcc776712015-02-17 20:18:47 -08002055 if (clientSp.get() != nullptr) {
2056 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002057 uid_t clientUid = clientSp->getClientUid();
2058 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002059 }
2060 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2061 PRId32 ", ", key.string(), cost, pid, priority);
2062
Ruben Brunk6267b532015-04-30 17:44:07 -07002063 if (clientSp.get() != nullptr) {
2064 ret.appendFormat("User Id: %d, ", clientUserId);
2065 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002066 if (packageName.size() != 0) {
2067 ret.appendFormat("Client Package Name: %s", packageName.string());
2068 }
2069
2070 ret.append(", Conflicting Client Devices: {");
2071 for (auto& j : conflicting) {
2072 ret.appendFormat("%s, ", j.string());
2073 }
2074 ret.append("})");
2075 }
2076 if (hasAny) ret.append("\n");
2077 ret.append("]\n");
2078 return ret;
2079}
2080
2081CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2082 const String8& key, const sp<BasicClient>& value, int32_t cost,
2083 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2084
2085 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2086 key, value, cost, conflictingKeys, priority, ownerId);
2087}
2088
2089CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2090 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2091 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2092 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2093}
2094
2095// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096
2097static const int kDumpLockRetries = 50;
2098static const int kDumpLockSleep = 60000;
2099
2100static bool tryLock(Mutex& mutex)
2101{
2102 bool locked = false;
2103 for (int i = 0; i < kDumpLockRetries; ++i) {
2104 if (mutex.tryLock() == NO_ERROR) {
2105 locked = true;
2106 break;
2107 }
2108 usleep(kDumpLockSleep);
2109 }
2110 return locked;
2111}
2112
2113status_t CameraService::dump(int fd, const Vector<String16>& args) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002114 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002116 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 "can't dump CameraService from pid=%d, uid=%d\n",
2118 getCallingPid(),
2119 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 write(fd, result.string(), result.size());
2121 } else {
2122 bool locked = tryLock(mServiceLock);
2123 // failed to lock - CameraService is probably deadlocked
2124 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002125 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002126 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 }
2128
2129 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002130 if (!mModule) {
2131 result = String8::format("No camera module available!\n");
2132 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002133
2134 // Dump event log for error information
2135 dumpEventLog(fd);
2136
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002137 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002138 return NO_ERROR;
2139 }
2140
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002141 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2142 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2143 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2144 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002145 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2146 String8 activeClientString = mActiveClientManager.toString();
2147 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002148 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002149
Ruben Brunkf81648e2014-04-17 16:14:57 -07002150 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2151 if (desc == NULL) {
2152 result.appendFormat("Vendor tags left unimplemented.\n");
2153 } else {
2154 result.appendFormat("Vendor tag definitions:\n");
2155 }
2156
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002157 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002158
2159 if (desc != NULL) {
2160 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2161 }
2162
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002163 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002164
2165 bool stateLocked = tryLock(mCameraStatesLock);
2166 if (!stateLocked) {
2167 result = String8::format("CameraStates in use, may be deadlocked\n");
2168 write(fd, result.string(), result.size());
2169 }
2170
2171 for (auto& state : mCameraStates) {
2172 String8 cameraId = state.first;
2173 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002174 camera_info info;
2175
Ruben Brunkcc776712015-02-17 20:18:47 -08002176 // TODO: Change getCameraInfo + HAL to use String cameraIds
2177 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002178 if (rc != OK) {
2179 result.appendFormat(" Error reading static information!\n");
2180 write(fd, result.string(), result.size());
2181 } else {
2182 result.appendFormat(" Facing: %s\n",
2183 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2184 result.appendFormat(" Orientation: %d\n", info.orientation);
2185 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002186 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002187 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2188 } else {
2189 deviceVersion = info.device_version;
2190 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002191
2192 auto conflicting = state.second->getConflicting();
2193 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2194 result.appendFormat(" Conflicting Devices:");
2195 for (auto& id : conflicting) {
2196 result.appendFormat(" %s", cameraId.string());
2197 }
2198 if (conflicting.size() == 0) {
2199 result.appendFormat(" NONE");
2200 }
2201 result.appendFormat("\n");
2202
2203 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002204 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2205 result.appendFormat(" Device static metadata:\n");
2206 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002207 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002208 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002209 } else {
2210 write(fd, result.string(), result.size());
2211 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002212
2213 CameraParameters p = state.second->getShimParams();
2214 if (!p.isEmpty()) {
2215 result = String8::format(" Camera1 API shim is using parameters:\n ");
2216 write(fd, result.string(), result.size());
2217 p.dump(fd, args);
2218 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002219 }
2220
Ruben Brunkcc776712015-02-17 20:18:47 -08002221 auto clientDescriptor = mActiveClientManager.get(cameraId);
2222 if (clientDescriptor == nullptr) {
2223 result = String8::format(" Device %s is closed, no client instance\n",
2224 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002225 write(fd, result.string(), result.size());
2226 continue;
2227 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002229 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2230 cameraId.string());
2231 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2232 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2233
2234 auto client = clientDescriptor->getValue();
2235 result.appendFormat("Client package: %s\n",
2236 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002237 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002238
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002239 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002241
2242 if (stateLocked) mCameraStatesLock.unlock();
2243
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002245 result = String8::format("\nNo active camera clients yet.\n");
2246 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 }
2248
2249 if (locked) mServiceLock.unlock();
2250
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002251 // Dump camera traces if there were any
2252 write(fd, "\n", 1);
2253 camera3::CameraTraces::dump(fd, args);
2254
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 // change logging level
2256 int n = args.size();
2257 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002258 String16 verboseOption("-v");
2259 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260 String8 levelStr(args[i+1]);
2261 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002262 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002264 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 }
2266 }
2267 }
2268 return NO_ERROR;
2269}
2270
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002271void CameraService::dumpEventLog(int fd) {
2272 String8 result = String8("\nPrior client events (most recent at top):\n");
2273
2274 Mutex::Autolock l(mLogLock);
2275 for (const auto& msg : mEventLog) {
2276 result.appendFormat(" %s\n", msg.string());
2277 }
2278
2279 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2280 result.append(" ...\n");
2281 } else if (mEventLog.size() == 0) {
2282 result.append(" [no events yet]\n");
2283 }
2284 result.append("\n");
2285
2286 write(fd, result.string(), result.size());
2287}
2288
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002289void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002290 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002291 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2292 if (mTorchClientMap[i] == who) {
2293 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002294 String8 cameraId = mTorchClientMap.keyAt(i);
2295 status_t res = mFlashlight->setTorchMode(cameraId, false);
2296 if (res) {
2297 ALOGE("%s: torch client died but couldn't turn off torch: "
2298 "%s (%d)", __FUNCTION__, strerror(-res), res);
2299 return;
2300 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002301 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002302 break;
2303 }
2304 }
2305}
2306
Ruben Brunkcc776712015-02-17 20:18:47 -08002307/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002308
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002309 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002310 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2311 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002312 */
2313
Ruben Brunka8ca9152015-04-07 14:23:40 -07002314 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2315
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002316 // check torch client
2317 handleTorchClientBinderDied(who);
2318
2319 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002320 if(!evictClientIdByRemote(who)) {
2321 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002322 return;
2323 }
2324
Ruben Brunkcc776712015-02-17 20:18:47 -08002325 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2326 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002327}
2328
Ruben Brunkcc776712015-02-17 20:18:47 -08002329void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2330 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002331}
2332
Ruben Brunkcc776712015-02-17 20:18:47 -08002333void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2334 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2335 // Do not lock mServiceLock here or can get into a deadlock from
2336 // connect() -> disconnect -> updateStatus
2337
2338 auto state = getCameraState(cameraId);
2339
2340 if (state == nullptr) {
2341 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2342 cameraId.string());
2343 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002344 }
2345
Ruben Brunkcc776712015-02-17 20:18:47 -08002346 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2347 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2348 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2349 (const String8& cameraId, ICameraServiceListener::Status status) {
2350
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002351 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2352 // Update torch status if it has a flash unit.
2353 Mutex::Autolock al(mTorchStatusMutex);
2354 ICameraServiceListener::TorchStatus torchStatus;
2355 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2356 NAME_NOT_FOUND) {
2357 ICameraServiceListener::TorchStatus newTorchStatus =
2358 status == ICameraServiceListener::STATUS_PRESENT ?
2359 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2360 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2361 if (torchStatus != newTorchStatus) {
2362 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2363 }
2364 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002365 }
2366
2367 Mutex::Autolock lock(mStatusListenerLock);
2368
2369 for (auto& listener : mListenerList) {
2370 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2371 int id = cameraIdToInt(cameraId);
2372 if (id != -1) listener->onStatusChanged(status, id);
2373 }
2374 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002375}
2376
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002377status_t CameraService::getTorchStatusLocked(
2378 const String8& cameraId,
2379 ICameraServiceListener::TorchStatus *status) const {
2380 if (!status) {
2381 return BAD_VALUE;
2382 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002383 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2384 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002385 // invalid camera ID or the camera doesn't have a flash unit
2386 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002387 }
2388
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002389 *status = mTorchStatusMap.valueAt(index);
2390 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002391}
2392
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002393status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002394 ICameraServiceListener::TorchStatus status) {
2395 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2396 if (index == NAME_NOT_FOUND) {
2397 return BAD_VALUE;
2398 }
2399 ICameraServiceListener::TorchStatus& item =
2400 mTorchStatusMap.editValueAt(index);
2401 item = status;
2402
2403 return OK;
2404}
2405
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406}; // namespace android