blob: 8c5c43aba7fa15cdba2d870e8358fd7829e7dbe9 [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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <utils/Errors.h>
44#include <utils/Log.h>
45#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080046#include <utils/Trace.h>
47#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070048#include <system/camera_metadata.h>
49#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
51#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070052#include "api1/CameraClient.h"
53#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070054#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070056#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
58namespace android {
59
60// ----------------------------------------------------------------------------
61// Logging support -- this is for debugging only
62// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070063volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Steve Blockb8a80522011-12-20 16:23:08 +000065#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
66#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070067
68static void setLogLevel(int level) {
69 android_atomic_write(level, &gLogLevel);
70}
71
72// ----------------------------------------------------------------------------
73
Igor Murashkincba2c162013-03-20 15:56:31 -070074extern "C" {
75static void camera_device_status_change(
76 const struct camera_module_callbacks* callbacks,
77 int camera_id,
78 int new_status) {
79 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080080 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070081
Ruben Brunkcc776712015-02-17 20:18:47 -080082 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
83 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070084}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080085
86static void torch_mode_status_change(
87 const struct camera_module_callbacks* callbacks,
88 const char* camera_id,
89 int new_status) {
90 if (!callbacks || !camera_id) {
91 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
92 callbacks, camera_id);
93 }
94 sp<CameraService> cs = const_cast<CameraService*>(
95 static_cast<const CameraService*>(callbacks));
96
97 ICameraServiceListener::TorchStatus status;
98 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -080099 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800100 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
101 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800102 case TORCH_MODE_STATUS_AVAILABLE_OFF:
103 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
104 break;
105 case TORCH_MODE_STATUS_AVAILABLE_ON:
106 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800107 break;
108 default:
109 ALOGE("Unknown torch status %d", new_status);
110 return;
111 }
112
113 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800114 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800115 status);
116}
Igor Murashkincba2c162013-03-20 15:56:31 -0700117} // extern "C"
118
Mathias Agopian65ab4712010-07-14 17:59:35 -0700119// ----------------------------------------------------------------------------
120
121// This is ugly and only safe if we never re-create the CameraService, but
122// should be ok for now.
123static CameraService *gCameraService;
124
Ruben Brunka8ca9152015-04-07 14:23:40 -0700125CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Ruben Brunk36597b22015-03-20 22:15:57 -0700126 mLastUserId(DEFAULT_LAST_USER_ID), mSoundRef(0), mModule(0), mFlashlight(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000127 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800129
Igor Murashkincba2c162013-03-20 15:56:31 -0700130 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800131 this->torch_mode_status_change = android::torch_mode_status_change;
132
Ruben Brunkcc776712015-02-17 20:18:47 -0800133 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134}
135
Iliyan Malchev8951a972011-04-14 16:55:59 -0700136void CameraService::onFirstRef()
137{
Ruben Brunkcc776712015-02-17 20:18:47 -0800138 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800139
Iliyan Malchev8951a972011-04-14 16:55:59 -0700140 BnCameraService::onFirstRef();
141
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800142 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700143 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
144 (const hw_module_t **)&rawModule);
145 if (err < 0) {
146 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
147 logServiceError("Could not load camera HAL module", err);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700148 mNumberOfCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700149 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700150 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800151
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700152 mModule = new CameraModule(rawModule);
153 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
154 err = mModule->init();
155 if (err != OK) {
156 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
157 strerror(-err));
158 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800159
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 mNumberOfCameras = 0;
161 delete mModule;
162 mModule = nullptr;
163 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700164 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700165
166 mNumberOfCameras = mModule->getNumberOfCameras();
167
168 mFlashlight = new CameraFlashlight(*mModule, *this);
169 status_t res = mFlashlight->findFlashUnits();
170 if (res) {
171 // impossible because we haven't open any camera devices.
172 ALOGE("Failed to find flash units.");
173 }
174
175 for (int i = 0; i < mNumberOfCameras; i++) {
176 String8 cameraId = String8::format("%d", i);
177
178 // Defaults to use for cost and conflicting devices
179 int cost = 100;
180 char** conflicting_devices = nullptr;
181 size_t conflicting_devices_length = 0;
182
183 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
184 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4) {
185 struct camera_info info;
186 status_t rc = mModule->getCameraInfo(i, &info);
187 if (rc == NO_ERROR) {
188 cost = info.resource_cost;
189 conflicting_devices = info.conflicting_devices;
190 conflicting_devices_length = info.conflicting_devices_length;
191 } else {
192 ALOGE("%s: Received error loading camera info for device %d, cost and"
193 " conflicting devices fields set to defaults for this device.",
194 __FUNCTION__, i);
195 }
196 }
197
198 std::set<String8> conflicting;
199 for (size_t i = 0; i < conflicting_devices_length; i++) {
200 conflicting.emplace(String8(conflicting_devices[i]));
201 }
202
203 // Initialize state for each camera device
204 {
205 Mutex::Autolock lock(mCameraStatesLock);
206 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
207 conflicting));
208 }
209
210 if (mFlashlight->hasFlashUnit(cameraId)) {
211 mTorchStatusMap.add(cameraId,
212 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
213 }
214 }
215
216 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
217 mModule->setCallbacks(this);
218 }
219
220 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
221
222 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
223 setUpVendorTags();
224 }
225
226 CameraDeviceFactory::registerService(this);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700227}
228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800230 if (mModule) {
231 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800232 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800233 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800234 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800235 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700236}
237
Ruben Brunkcc776712015-02-17 20:18:47 -0800238void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
239 camera_device_status_t newStatus) {
240 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700241 cameraId, newStatus);
242
Ruben Brunkcc776712015-02-17 20:18:47 -0800243 String8 id = String8::format("%d", cameraId);
244 std::shared_ptr<CameraState> state = getCameraState(id);
245
246 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700247 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
248 return;
249 }
250
Ruben Brunkcc776712015-02-17 20:18:47 -0800251 ICameraServiceListener::Status oldStatus = state->getStatus();
252
253 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
254 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700255 return;
256 }
257
Igor Murashkincba2c162013-03-20 15:56:31 -0700258 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700259 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
260 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800261 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700262 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800263 // Don't do this in updateStatus to avoid deadlock over mServiceLock
264 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700265
Ruben Brunkcc776712015-02-17 20:18:47 -0800266 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
267 // to this device until the status changes
268 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700269
Ruben Brunkcc776712015-02-17 20:18:47 -0800270 // Remove cached shim parameters
271 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700272
Ruben Brunkcc776712015-02-17 20:18:47 -0800273 // Remove the client from the list of active clients
274 clientToDisconnect = removeClientLocked(id);
275
276 // Notify the client of disconnection
277 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
278 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700279 }
280
Ruben Brunkcc776712015-02-17 20:18:47 -0800281 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
282 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700283
Ruben Brunkcc776712015-02-17 20:18:47 -0800284 // Disconnect client
285 if (clientToDisconnect.get() != nullptr) {
286 // Ensure not in binder RPC so client disconnect PID checks work correctly
287 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
288 "onDeviceStatusChanged must be called from the camera service process!");
289 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700290 }
291
Ruben Brunkcc776712015-02-17 20:18:47 -0800292 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700293 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
294 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
295 newStatus));
296 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800297 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700298 }
299
Igor Murashkincba2c162013-03-20 15:56:31 -0700300}
301
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800302void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800303 ICameraServiceListener::TorchStatus newStatus) {
304 Mutex::Autolock al(mTorchStatusMutex);
305 onTorchStatusChangedLocked(cameraId, newStatus);
306}
307
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800308void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800309 ICameraServiceListener::TorchStatus newStatus) {
310 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
311 __FUNCTION__, cameraId.string(), newStatus);
312
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800313 ICameraServiceListener::TorchStatus status;
314 status_t res = getTorchStatusLocked(cameraId, &status);
315 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700316 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
317 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800318 return;
319 }
320 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800321 return;
322 }
323
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800324 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800325 if (res) {
326 ALOGE("%s: Failed to set the torch status", __FUNCTION__,
327 (uint32_t)newStatus);
328 return;
329 }
330
Ruben Brunkcc776712015-02-17 20:18:47 -0800331 {
332 Mutex::Autolock lock(mStatusListenerLock);
333 for (auto& i : mListenerList) {
334 i->onTorchStatusChanged(newStatus, String16{cameraId});
335 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800336 }
337}
338
339
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340int32_t CameraService::getNumberOfCameras() {
341 return mNumberOfCameras;
342}
343
344status_t CameraService::getCameraInfo(int cameraId,
345 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700346 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700347 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700348 }
349
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
351 return BAD_VALUE;
352 }
353
Iliyan Malchev8951a972011-04-14 16:55:59 -0700354 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700355 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800356 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700357 cameraInfo->facing = info.facing;
358 cameraInfo->orientation = info.orientation;
359 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360}
361
Ruben Brunkcc776712015-02-17 20:18:47 -0800362int CameraService::cameraIdToInt(const String8& cameraId) {
363 errno = 0;
364 size_t pos = 0;
365 int ret = stoi(std::string{cameraId.string()}, &pos);
366 if (errno != 0 || pos != cameraId.size()) {
367 return -1;
368 }
369 return ret;
370}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700371
372status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
373 status_t ret = OK;
374 struct CameraInfo info;
375 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
376 return ret;
377 }
378
379 CameraMetadata shimInfo;
380 int32_t orientation = static_cast<int32_t>(info.orientation);
381 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
382 return ret;
383 }
384
385 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
386 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
387 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
388 return ret;
389 }
390
Igor Murashkin65d14b92014-06-17 12:03:20 -0700391 CameraParameters shimParams;
392 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
393 // Error logged by callee
394 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700395 }
396
397 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700398 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700399 Vector<int32_t> formats;
400 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700401 {
402 shimParams.getSupportedPreviewSizes(/*out*/sizes);
403 shimParams.getSupportedPreviewFormats(/*out*/formats);
404 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700405 }
406
407 // Always include IMPLEMENTATION_DEFINED
408 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
409
410 const size_t INTS_PER_CONFIG = 4;
411
412 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700413 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
414
415 Vector<int32_t> streamConfigs;
416 streamConfigs.setCapacity(streamConfigSize);
417
Ruben Brunkb2119af2014-05-09 19:57:56 -0700418 for (size_t i = 0; i < formats.size(); ++i) {
419 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700420 streamConfigs.add(formats[i]);
421 streamConfigs.add(sizes[j].width);
422 streamConfigs.add(sizes[j].height);
423 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700424 }
425 }
426
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700427 for (size_t i = 0; i < jpegSizes.size(); ++i) {
428 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
429 streamConfigs.add(jpegSizes[i].width);
430 streamConfigs.add(jpegSizes[i].height);
431 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
432 }
433
Ruben Brunkb2119af2014-05-09 19:57:56 -0700434 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700435 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700436 return ret;
437 }
438
439 int64_t fakeMinFrames[0];
440 // TODO: Fixme, don't fake min frame durations.
441 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
442 fakeMinFrames, 0)) != OK) {
443 return ret;
444 }
445
446 int64_t fakeStalls[0];
447 // TODO: Fixme, don't fake stall durations.
448 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
449 fakeStalls, 0)) != OK) {
450 return ret;
451 }
452
453 *cameraInfo = shimInfo;
454 return OK;
455}
456
Zhijun He2b59be82013-09-25 10:14:30 -0700457status_t CameraService::getCameraCharacteristics(int cameraId,
458 CameraMetadata* cameraInfo) {
459 if (!cameraInfo) {
460 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
461 return BAD_VALUE;
462 }
463
464 if (!mModule) {
465 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
466 return -ENODEV;
467 }
468
Zhijun He2b59be82013-09-25 10:14:30 -0700469 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
470 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
471 return BAD_VALUE;
472 }
473
474 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700475 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800476 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700477 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
478 /**
479 * Backwards compatibility mode for old HALs:
480 * - Convert CameraInfo into static CameraMetadata properties.
481 * - Retrieve cached CameraParameters for this camera. If none exist,
482 * attempt to open CameraClient and retrieve the CameraParameters.
483 * - Convert cached CameraParameters into static CameraMetadata
484 * properties.
485 */
486 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700487
Ruben Brunkb2119af2014-05-09 19:57:56 -0700488 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
489 return ret;
490 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700491
Ruben Brunkb2119af2014-05-09 19:57:56 -0700492 } else {
493 /**
494 * Normal HAL 2.1+ codepath.
495 */
496 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800497 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700498 *cameraInfo = info.static_camera_characteristics;
499 }
Zhijun He2b59be82013-09-25 10:14:30 -0700500
501 return ret;
502}
503
Ruben Brunkcc776712015-02-17 20:18:47 -0800504int CameraService::getCallingPid() {
505 return IPCThreadState::self()->getCallingPid();
506}
507
508int CameraService::getCallingUid() {
509 return IPCThreadState::self()->getCallingUid();
510}
511
512String8 CameraService::getFormattedCurrentTime() {
513 time_t now = time(nullptr);
514 char formattedTime[64];
515 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
516 return String8(formattedTime);
517}
518
519int CameraService::getCameraPriorityFromProcState(int procState) {
520 // Find the priority for the camera usage based on the process state. Higher priority clients
521 // win for evictions.
522 // Note: Unlike the ordering for ActivityManager, persistent system processes will always lose
523 // the camera to the top/foreground applications.
524 switch(procState) {
525 case PROCESS_STATE_TOP: // User visible
526 return 100;
527 case PROCESS_STATE_IMPORTANT_FOREGROUND: // Foreground
528 return 90;
529 case PROCESS_STATE_PERSISTENT: // Persistent system services
530 case PROCESS_STATE_PERSISTENT_UI:
531 return 80;
532 case PROCESS_STATE_IMPORTANT_BACKGROUND: // "Important" background processes
533 return 70;
534 case PROCESS_STATE_BACKUP: // Everything else
535 case PROCESS_STATE_HEAVY_WEIGHT:
536 case PROCESS_STATE_SERVICE:
537 case PROCESS_STATE_RECEIVER:
538 case PROCESS_STATE_HOME:
539 case PROCESS_STATE_LAST_ACTIVITY:
540 case PROCESS_STATE_CACHED_ACTIVITY:
541 case PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
542 case PROCESS_STATE_CACHED_EMPTY:
543 return 1;
544 case PROCESS_STATE_NONEXISTENT:
545 return -1;
546 default:
547 ALOGE("%s: Received unknown process state from ActivityManagerService!", __FUNCTION__);
548 return -1;
549 }
550}
551
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800552status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
553 if (!mModule) {
554 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
555 return -ENODEV;
556 }
557
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800558 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
559 return OK;
560}
561
Igor Murashkin634a5152013-02-20 17:15:11 -0800562int CameraService::getDeviceVersion(int cameraId, int* facing) {
563 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800564 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800565 return -1;
566 }
567
568 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800569 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800570 deviceVersion = info.device_version;
571 } else {
572 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
573 }
574
575 if (facing) {
576 *facing = info.facing;
577 }
578
579 return deviceVersion;
580}
581
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700582status_t CameraService::filterGetInfoErrorCode(status_t err) {
583 switch(err) {
584 case NO_ERROR:
585 case -EINVAL:
586 return err;
587 default:
588 break;
589 }
590 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800591}
592
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800593bool CameraService::setUpVendorTags() {
594 vendor_tag_ops_t vOps = vendor_tag_ops_t();
595
596 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800597 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800598 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
599 return false;
600 }
601
602 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800603 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800604 ATRACE_END();
605
606 // Ensure all vendor operations are present
607 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
608 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
609 vOps.get_tag_type == NULL) {
610 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
611 , __FUNCTION__);
612 return false;
613 }
614
615 // Read all vendor tag definitions into a descriptor
616 sp<VendorTagDescriptor> desc;
617 status_t res;
618 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
619 != OK) {
620 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
621 "received error %s (%d). Camera clients will not be able to use"
622 "vendor tags", __FUNCTION__, strerror(res), res);
623 return false;
624 }
625
626 // Set the global descriptor to use with camera metadata
627 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
628 return true;
629}
630
Ruben Brunkcc776712015-02-17 20:18:47 -0800631status_t CameraService::makeClient(const sp<CameraService>& cameraService,
632 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
633 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
634 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
635 /*out*/sp<BasicClient>* client) {
636
637 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
638 int id = cameraIdToInt(cameraId);
639 if (id == -1) {
640 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
641 cameraId.string());
642 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700643 }
644
Ruben Brunkcc776712015-02-17 20:18:47 -0800645 if (halVersion < 0 || halVersion == deviceVersion) {
646 // Default path: HAL version is unspecified by caller, create CameraClient
647 // based on device version reported by the HAL.
648 switch(deviceVersion) {
649 case CAMERA_DEVICE_API_VERSION_1_0:
650 if (effectiveApiLevel == API_1) { // Camera1 API route
651 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
652 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
653 clientPid, clientUid, getpid(), legacyMode);
654 } else { // Camera2 API route
655 ALOGW("Camera using old HAL version: %d", deviceVersion);
656 return -EOPNOTSUPP;
657 }
658 break;
659 case CAMERA_DEVICE_API_VERSION_2_0:
660 case CAMERA_DEVICE_API_VERSION_2_1:
661 case CAMERA_DEVICE_API_VERSION_3_0:
662 case CAMERA_DEVICE_API_VERSION_3_1:
663 case CAMERA_DEVICE_API_VERSION_3_2:
664 case CAMERA_DEVICE_API_VERSION_3_3:
665 if (effectiveApiLevel == API_1) { // Camera1 API route
666 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
667 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
668 clientPid, clientUid, servicePid, legacyMode);
669 } else { // Camera2 API route
670 sp<ICameraDeviceCallbacks> tmp =
671 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
672 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
673 facing, clientPid, clientUid, servicePid);
674 }
675 break;
676 default:
677 // Should not be reachable
678 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
679 return INVALID_OPERATION;
680 }
681 } else {
682 // A particular HAL version is requested by caller. Create CameraClient
683 // based on the requested HAL version.
684 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
685 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
686 // Only support higher HAL version device opened as HAL1.0 device.
687 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
688 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
689 clientPid, clientUid, servicePid, legacyMode);
690 } else {
691 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
692 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
693 " opened as HAL %x device", halVersion, deviceVersion,
694 CAMERA_DEVICE_API_VERSION_1_0);
695 return INVALID_OPERATION;
696 }
697 }
698 return NO_ERROR;
699}
700
701status_t CameraService::initializeShimMetadata(int cameraId) {
702 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700703
704 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800705 String8 id = String8::format("%d", cameraId);
706 status_t ret = NO_ERROR;
707 sp<Client> tmp = nullptr;
708 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
709 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
710 false, true, tmp)) != NO_ERROR) {
711 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
712 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700713 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800714 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700715}
716
Igor Murashkin65d14b92014-06-17 12:03:20 -0700717status_t CameraService::getLegacyParametersLazy(int cameraId,
718 /*out*/
719 CameraParameters* parameters) {
720
721 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
722
723 status_t ret = 0;
724
725 if (parameters == NULL) {
726 ALOGE("%s: parameters must not be null", __FUNCTION__);
727 return BAD_VALUE;
728 }
729
Ruben Brunkcc776712015-02-17 20:18:47 -0800730 String8 id = String8::format("%d", cameraId);
731
732 // Check if we already have parameters
733 {
734 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700735 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800736 auto cameraState = getCameraState(id);
737 if (cameraState == nullptr) {
738 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
739 return BAD_VALUE;
740 }
741 CameraParameters p = cameraState->getShimParams();
742 if (!p.isEmpty()) {
743 *parameters = p;
744 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700745 }
746 }
747
Ruben Brunkcc776712015-02-17 20:18:47 -0800748 int64_t token = IPCThreadState::self()->clearCallingIdentity();
749 ret = initializeShimMetadata(cameraId);
750 IPCThreadState::self()->restoreCallingIdentity(token);
751 if (ret != NO_ERROR) {
752 // Error already logged by callee
753 return ret;
754 }
755
756 // Check for parameters again
757 {
758 // Scope for service lock
759 Mutex::Autolock lock(mServiceLock);
760 auto cameraState = getCameraState(id);
761 if (cameraState == nullptr) {
762 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
763 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700764 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800765 CameraParameters p = cameraState->getShimParams();
766 if (!p.isEmpty()) {
767 *parameters = p;
768 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700769 }
770 }
771
Ruben Brunkcc776712015-02-17 20:18:47 -0800772 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
773 __FUNCTION__);
774 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700775}
776
Ruben Brunk36597b22015-03-20 22:15:57 -0700777status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
778 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800779
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500781
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800782 if (clientUid == USE_CALLING_UID) {
783 clientUid = getCallingUid();
784 } else {
785 // We only trust our own process to forward client UIDs
786 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700787 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
788 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700789 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800790 }
791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792
Iliyan Malchev8951a972011-04-14 16:55:59 -0700793 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800794 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
795 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700796 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700797 }
798
Ruben Brunkcc776712015-02-17 20:18:47 -0800799 if (getCameraState(cameraId) == nullptr) {
800 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
801 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700802 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803 }
804
Ruben Brunkcc776712015-02-17 20:18:47 -0800805 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800806 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800807 char key[PROPERTY_KEY_MAX];
808 int clientUserId = multiuser_get_user_id(clientUid);
809 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
810 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800811 if (strcmp(value, "1") == 0) {
812 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800813 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
814 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700815 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800816 }
817
Ruben Brunka8ca9152015-04-07 14:23:40 -0700818 // Only allow clients who are being used by the current foreground device user, unless calling
819 // from our own process.
820 if (callingPid != getpid() &&
821 (mLastUserId != clientUserId && mLastUserId != DEFAULT_LAST_USER_ID)) {
822 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from previous "
823 "device user %d, current device user %d)", callingPid, clientUserId, mLastUserId);
Ruben Brunk36597b22015-03-20 22:15:57 -0700824 return PERMISSION_DENIED;
825 }
826
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 return checkIfDeviceIsUsable(cameraId);
828}
829
830status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
831 auto cameraState = getCameraState(cameraId);
832 int callingPid = getCallingPid();
833 if (cameraState == nullptr) {
834 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
835 cameraId.string());
836 return -ENODEV;
837 }
838
839 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700840 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800841 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
842 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700843 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700844 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800845 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
846 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700847 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700848 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700849
Ruben Brunkcc776712015-02-17 20:18:47 -0800850 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800851}
852
Ruben Brunkcc776712015-02-17 20:18:47 -0800853void CameraService::finishConnectLocked(const sp<BasicClient>& client,
854 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800855
Ruben Brunkcc776712015-02-17 20:18:47 -0800856 // Make a descriptor for the incoming client
857 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
858 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
859
860 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
861 String8(client->getPackageName()));
862
863 if (evicted.size() > 0) {
864 // This should never happen - clients should already have been removed in disconnect
865 for (auto& i : evicted) {
866 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
867 __FUNCTION__, i->getKey().string());
868 }
869
870 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
871 __FUNCTION__);
872 }
873}
874
875status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
876 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
877 /*out*/
878 sp<BasicClient>* client,
879 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
880
881 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700882 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800883 DescriptorPtr clientDescriptor;
884 {
885 if (effectiveApiLevel == API_1) {
886 // If we are using API1, any existing client for this camera ID with the same remote
887 // should be returned rather than evicted to allow MediaRecorder to work properly.
888
889 auto current = mActiveClientManager.get(cameraId);
890 if (current != nullptr) {
891 auto clientSp = current->getValue();
892 if (clientSp.get() != nullptr) { // should never be needed
893 if (clientSp->getRemote() == remoteCallback) {
894 ALOGI("CameraService::connect X (PID %d) (second call from same"
895 "app binder, returning the same client)", clientPid);
896 *client = clientSp;
897 return NO_ERROR;
898 }
899 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800900 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800901 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800902
Ruben Brunkcc776712015-02-17 20:18:47 -0800903 // Return error if the device was unplugged or removed by the HAL for some reason
904 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
905 return ret;
906 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800907
Ruben Brunkcc776712015-02-17 20:18:47 -0800908 // Get current active client PIDs
909 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
910 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800911
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700912 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
913 // address of PROCESS_STATE_NONEXISTENT as a reference argument
914 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
915 // not have an out-of-class definition.
916 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800917
Ruben Brunkcc776712015-02-17 20:18:47 -0800918 // Get priorites of all active PIDs
919 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
920 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700921
Ruben Brunkcc776712015-02-17 20:18:47 -0800922 // Update all active clients' priorities
923 std::map<int,int> pidToPriorityMap;
924 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
925 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
926 }
927 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800928
Ruben Brunkcc776712015-02-17 20:18:47 -0800929 // Get state for the given cameraId
930 auto state = getCameraState(cameraId);
931 if (state == nullptr) {
932 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
933 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700934 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -0700935 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800936
937 // Make descriptor for incoming client
938 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
939 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
940 state->getConflicting(),
941 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
942
943 // Find clients that would be evicted
944 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
945
946 // If the incoming client was 'evicted,' higher priority clients have the camera in the
947 // background, so we cannot do evictions
948 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
949 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
950 " priority).", clientPid);
951
952 sp<BasicClient> clientSp = clientDescriptor->getValue();
953 String8 curTime = getFormattedCurrentTime();
954 auto incompatibleClients =
955 mActiveClientManager.getIncompatibleClients(clientDescriptor);
956
957 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -0700958 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800959 cameraId.string(), packageName.string(), clientPid,
960 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
961
962 for (auto& i : incompatibleClients) {
963 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
964 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
965 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
966 i->getPriority());
967 }
968
969 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -0700970 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800971 mEventLog.add(msg);
972
973 return -EBUSY;
974 }
975
976 for (auto& i : evicted) {
977 sp<BasicClient> clientSp = i->getValue();
978 if (clientSp.get() == nullptr) {
979 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
980
981 // TODO: Remove this
982 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
983 __FUNCTION__);
984 mActiveClientManager.remove(i);
985 continue;
986 }
987
988 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
989 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700990 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -0800991
Ruben Brunkcc776712015-02-17 20:18:47 -0800992 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -0700993 logEvent(String8::format("EVICT device %s client held by package %s (PID"
994 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
995 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -0800996 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
997 i->getOwnerId(), i->getPriority(), cameraId.string(),
998 packageName.string(), clientPid,
999 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1000
1001 // Notify the client of disconnection
1002 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1003 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001004 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001005 }
1006
Ruben Brunkcc776712015-02-17 20:18:47 -08001007 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1008 // other clients from connecting in mServiceLockWrapper if held
1009 mServiceLock.unlock();
1010
1011 // Clear caller identity temporarily so client disconnect PID checks work correctly
1012 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1013
1014 // Destroy evicted clients
1015 for (auto& i : evictedClients) {
1016 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001017 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001018 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001019
1020 IPCThreadState::self()->restoreCallingIdentity(token);
1021
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001022 for (const auto& i : evictedClients) {
1023 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1024 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1025 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1026 if (ret == TIMED_OUT) {
1027 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1028 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1029 mActiveClientManager.toString().string());
1030 return -EBUSY;
1031 }
1032 if (ret != NO_ERROR) {
1033 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1034 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1035 ret, mActiveClientManager.toString().string());
1036 return ret;
1037 }
1038 }
1039
1040 evictedClients.clear();
1041
Ruben Brunkcc776712015-02-17 20:18:47 -08001042 // Once clients have been disconnected, relock
1043 mServiceLock.lock();
1044
1045 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1046 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1047 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001048 }
1049
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 *partial = clientDescriptor;
1051 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001052}
1053
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001054status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001055 const sp<ICameraClient>& cameraClient,
1056 int cameraId,
1057 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001058 int clientUid,
1059 /*out*/
1060 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001061
Ruben Brunkcc776712015-02-17 20:18:47 -08001062 status_t ret = NO_ERROR;
1063 String8 id = String8::format("%d", cameraId);
1064 sp<Client> client = nullptr;
1065 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
1066 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001067
Ruben Brunkcc776712015-02-17 20:18:47 -08001068 if(ret != NO_ERROR) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001069 logRejected(id, getCallingPid(), String8(clientPackageName),
1070 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001071 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 }
1073
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001074 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001075 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076}
1077
Zhijun Heb10cdad2014-06-16 16:38:35 -07001078status_t CameraService::connectLegacy(
1079 const sp<ICameraClient>& cameraClient,
1080 int cameraId, int halVersion,
1081 const String16& clientPackageName,
1082 int clientUid,
1083 /*out*/
1084 sp<ICamera>& device) {
1085
Ruben Brunka8ca9152015-04-07 14:23:40 -07001086 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001087 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001088 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001089 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001090 /*
1091 * Either the HAL version is unspecified in which case this just creates
1092 * a camera client selected by the latest device version, or
1093 * it's a particular version in which case the HAL must supported
1094 * the open_legacy call
1095 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001096 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001097 __FUNCTION__, apiVersion);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001098 logRejected(id, getCallingPid(), String8(clientPackageName),
1099 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001100 return INVALID_OPERATION;
1101 }
1102
Ruben Brunkcc776712015-02-17 20:18:47 -08001103 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001104 sp<Client> client = nullptr;
1105 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
1106 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001107
Ruben Brunkcc776712015-02-17 20:18:47 -08001108 if(ret != NO_ERROR) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001109 logRejected(id, getCallingPid(), String8(clientPackageName),
1110 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001111 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001112 }
1113
Zhijun Heb10cdad2014-06-16 16:38:35 -07001114 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001115 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001116}
1117
Ruben Brunkcc776712015-02-17 20:18:47 -08001118status_t CameraService::connectDevice(
1119 const sp<ICameraDeviceCallbacks>& cameraCb,
1120 int cameraId,
1121 const String16& clientPackageName,
1122 int clientUid,
1123 /*out*/
1124 sp<ICameraDeviceUser>& device) {
1125
1126 status_t ret = NO_ERROR;
1127 String8 id = String8::format("%d", cameraId);
1128 sp<CameraDeviceClient> client = nullptr;
1129 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1130 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
1131 /*out*/client);
1132
1133 if(ret != NO_ERROR) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001134 logRejected(id, getCallingPid(), String8(clientPackageName),
1135 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001136 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001137 }
1138
Ruben Brunkcc776712015-02-17 20:18:47 -08001139 device = client;
1140 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001141}
1142
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001143status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1144 const sp<IBinder>& clientBinder) {
1145 if (enabled && clientBinder == NULL) {
1146 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001147 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001148 }
1149
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001150 String8 id = String8(cameraId.string());
1151
1152 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001153 auto state = getCameraState(id);
1154 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001155 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001156 return -EINVAL;
1157 }
1158
1159 ICameraServiceListener::Status cameraStatus = state->getStatus();
1160 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1161 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001162 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001163 return -EINVAL;
1164 }
1165
1166 {
1167 Mutex::Autolock al(mTorchStatusMutex);
1168 ICameraServiceListener::TorchStatus status;
1169 status_t res = getTorchStatusLocked(id, &status);
1170 if (res) {
1171 ALOGE("%s: getting current torch status failed for camera %s",
1172 __FUNCTION__, id.string());
1173 return -EINVAL;
1174 }
1175
1176 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001177 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001178 ALOGE("%s: torch mode of camera %s is not available because "
1179 "camera is in use", __FUNCTION__, id.string());
1180 return -EBUSY;
1181 } else {
1182 ALOGE("%s: torch mode of camera %s is not available due to "
1183 "insufficient resources", __FUNCTION__, id.string());
1184 return -EUSERS;
1185 }
1186 }
1187 }
1188
1189 status_t res = mFlashlight->setTorchMode(id, enabled);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001190 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001191 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1192 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001193 return res;
1194 }
1195
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001196 {
1197 // update the link to client's death
1198 Mutex::Autolock al(mTorchClientMapMutex);
1199 ssize_t index = mTorchClientMap.indexOfKey(id);
1200 if (enabled) {
1201 if (index == NAME_NOT_FOUND) {
1202 mTorchClientMap.add(id, clientBinder);
1203 } else {
1204 const sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
1205 oldBinder->unlinkToDeath(this);
1206
1207 mTorchClientMap.replaceValueAt(index, clientBinder);
1208 }
1209 clientBinder->linkToDeath(this);
1210 } else if (index != NAME_NOT_FOUND) {
1211 sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001212 oldBinder->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001213 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001214 }
1215
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001216 return OK;
1217}
1218
Ruben Brunk36597b22015-03-20 22:15:57 -07001219void CameraService::notifySystemEvent(int eventId, int arg0) {
1220 switch(eventId) {
1221 case ICameraService::USER_SWITCHED: {
1222 doUserSwitch(/*newUserId*/arg0);
1223 break;
1224 }
1225 case ICameraService::NO_EVENT:
1226 default: {
1227 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1228 eventId);
1229 break;
1230 }
1231 }
1232}
1233
Igor Murashkinbfc99152013-02-27 12:55:20 -08001234status_t CameraService::addListener(
1235 const sp<ICameraServiceListener>& listener) {
1236 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001237
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001238 if (listener == 0) {
1239 ALOGE("%s: Listener must not be null", __FUNCTION__);
1240 return BAD_VALUE;
1241 }
1242
Igor Murashkinbfc99152013-02-27 12:55:20 -08001243 Mutex::Autolock lock(mServiceLock);
1244
Ruben Brunkcc776712015-02-17 20:18:47 -08001245 {
1246 Mutex::Autolock lock(mStatusListenerLock);
1247 for (auto& it : mListenerList) {
1248 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1249 ALOGW("%s: Tried to add listener %p which was already subscribed",
1250 __FUNCTION__, listener.get());
1251 return ALREADY_EXISTS;
1252 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001253 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001254
1255 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001256 }
1257
Igor Murashkinbfc99152013-02-27 12:55:20 -08001258
Igor Murashkincba2c162013-03-20 15:56:31 -07001259 /* Immediately signal current status to this listener only */
1260 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 Mutex::Autolock lock(mCameraStatesLock);
1262 for (auto& i : mCameraStates) {
1263 // TODO: Update binder to use String16 for camera IDs and remove;
1264 int id = cameraIdToInt(i.first);
1265 if (id == -1) continue;
1266
1267 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001268 }
1269 }
1270
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001271 /* Immediately signal current torch status to this listener only */
1272 {
1273 Mutex::Autolock al(mTorchStatusMutex);
1274 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001275 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1276 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001277 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001278 }
1279
Igor Murashkinbfc99152013-02-27 12:55:20 -08001280 return OK;
1281}
Ruben Brunkcc776712015-02-17 20:18:47 -08001282
1283status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001284 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1285
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001286 if (listener == 0) {
1287 ALOGE("%s: Listener must not be null", __FUNCTION__);
1288 return BAD_VALUE;
1289 }
1290
Igor Murashkinbfc99152013-02-27 12:55:20 -08001291 Mutex::Autolock lock(mServiceLock);
1292
Ruben Brunkcc776712015-02-17 20:18:47 -08001293 {
1294 Mutex::Autolock lock(mStatusListenerLock);
1295 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1296 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1297 mListenerList.erase(it);
1298 return OK;
1299 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001300 }
1301 }
1302
1303 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1304 __FUNCTION__, listener.get());
1305
1306 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001307}
1308
Ruben Brunkcc776712015-02-17 20:18:47 -08001309status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001310 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1311
1312 if (parameters == NULL) {
1313 ALOGE("%s: parameters must not be null", __FUNCTION__);
1314 return BAD_VALUE;
1315 }
1316
1317 status_t ret = 0;
1318
1319 CameraParameters shimParams;
1320 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1321 // Error logged by caller
1322 return ret;
1323 }
1324
1325 String8 shimParamsString8 = shimParams.flatten();
1326 String16 shimParamsString16 = String16(shimParamsString8);
1327
1328 *parameters = shimParamsString16;
1329
1330 return OK;
1331}
1332
1333status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1334 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1335
1336 switch (apiVersion) {
1337 case API_VERSION_1:
1338 case API_VERSION_2:
1339 break;
1340 default:
1341 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1342 return BAD_VALUE;
1343 }
1344
1345 int facing = -1;
1346 int deviceVersion = getDeviceVersion(cameraId, &facing);
1347
1348 switch(deviceVersion) {
1349 case CAMERA_DEVICE_API_VERSION_1_0:
1350 case CAMERA_DEVICE_API_VERSION_2_0:
1351 case CAMERA_DEVICE_API_VERSION_2_1:
1352 case CAMERA_DEVICE_API_VERSION_3_0:
1353 case CAMERA_DEVICE_API_VERSION_3_1:
1354 if (apiVersion == API_VERSION_2) {
1355 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1356 __FUNCTION__, cameraId);
1357 return -EOPNOTSUPP;
1358 } else { // if (apiVersion == API_VERSION_1) {
1359 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1360 __FUNCTION__, cameraId);
1361 return OK;
1362 }
1363 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001364 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001365 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1366 __FUNCTION__, cameraId);
1367 return OK;
1368 case -1:
1369 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1370 return BAD_VALUE;
1371 default:
1372 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1373 return INVALID_OPERATION;
1374 }
1375
1376 return OK;
1377}
1378
Ruben Brunkcc776712015-02-17 20:18:47 -08001379void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001380 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001381 for (auto& i : mActiveClientManager.getAll()) {
1382 auto clientSp = i->getValue();
1383 if (clientSp.get() == client) {
1384 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001385 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001386 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001387}
1388
Ruben Brunkcc776712015-02-17 20:18:47 -08001389bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1390 const int callingPid = getCallingPid();
1391 const int servicePid = getpid();
1392 bool ret = false;
1393 {
1394 // Acquire mServiceLock and prevent other clients from connecting
1395 std::unique_ptr<AutoConditionLock> lock =
1396 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001397
Igor Murashkin634a5152013-02-20 17:15:11 -08001398
Ruben Brunkcc776712015-02-17 20:18:47 -08001399 std::vector<sp<BasicClient>> evicted;
1400 for (auto& i : mActiveClientManager.getAll()) {
1401 auto clientSp = i->getValue();
1402 if (clientSp.get() == nullptr) {
1403 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1404 mActiveClientManager.remove(i);
1405 continue;
1406 }
1407 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1408 callingPid == clientSp->getClientPid())) {
1409 mActiveClientManager.remove(i);
1410 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001411
Ruben Brunkcc776712015-02-17 20:18:47 -08001412 // Notify the client of disconnection
1413 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1414 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001415 }
1416 }
1417
Ruben Brunkcc776712015-02-17 20:18:47 -08001418 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1419 // other clients from connecting in mServiceLockWrapper if held
1420 mServiceLock.unlock();
1421
Ruben Brunk36597b22015-03-20 22:15:57 -07001422 // Do not clear caller identity, remote caller should be client proccess
1423
Ruben Brunkcc776712015-02-17 20:18:47 -08001424 for (auto& i : evicted) {
1425 if (i.get() != nullptr) {
1426 i->disconnect();
1427 ret = true;
1428 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001429 }
1430
Ruben Brunkcc776712015-02-17 20:18:47 -08001431 // Reacquire mServiceLock
1432 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001433
Ruben Brunkcc776712015-02-17 20:18:47 -08001434 } // lock is destroyed, allow further connect calls
1435
1436 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001437}
1438
Igor Murashkinecf17e82012-10-02 16:05:11 -07001439
Ruben Brunkcc776712015-02-17 20:18:47 -08001440std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1441 const String8& cameraId) const {
1442 std::shared_ptr<CameraState> state;
1443 {
1444 Mutex::Autolock lock(mCameraStatesLock);
1445 auto iter = mCameraStates.find(cameraId);
1446 if (iter != mCameraStates.end()) {
1447 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448 }
1449 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001450 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451}
1452
Ruben Brunkcc776712015-02-17 20:18:47 -08001453sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1454 // Remove from active clients list
1455 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1456 if (clientDescriptorPtr == nullptr) {
1457 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1458 cameraId.string());
1459 return sp<BasicClient>{nullptr};
1460 }
1461
1462 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001463}
1464
Ruben Brunk36597b22015-03-20 22:15:57 -07001465void CameraService::doUserSwitch(int newUserId) {
1466 // Acquire mServiceLock and prevent other clients from connecting
1467 std::unique_ptr<AutoConditionLock> lock =
1468 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1469
1470 if (newUserId <= 0) {
1471 ALOGW("%s: Bad user ID %d given during user switch, resetting to default.", __FUNCTION__,
1472 newUserId);
1473 newUserId = DEFAULT_LAST_USER_ID;
1474 }
1475
Ruben Brunka8ca9152015-04-07 14:23:40 -07001476 logUserSwitch(mLastUserId, newUserId);
1477
Ruben Brunk36597b22015-03-20 22:15:57 -07001478 mLastUserId = newUserId;
1479
1480 // Current user has switched, evict all current clients.
1481 std::vector<sp<BasicClient>> evicted;
1482 for (auto& i : mActiveClientManager.getAll()) {
1483 auto clientSp = i->getValue();
1484
1485 if (clientSp.get() == nullptr) {
1486 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1487 continue;
1488 }
1489
1490 evicted.push_back(clientSp);
1491
1492 String8 curTime = getFormattedCurrentTime();
1493
1494 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1495 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001496
Ruben Brunk36597b22015-03-20 22:15:57 -07001497 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001498 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001499 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001500 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1501 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001502
1503 }
1504
1505 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1506 // blocking other clients from connecting in mServiceLockWrapper if held.
1507 mServiceLock.unlock();
1508
1509 // Clear caller identity temporarily so client disconnect PID checks work correctly
1510 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1511
1512 for (auto& i : evicted) {
1513 i->disconnect();
1514 }
1515
1516 IPCThreadState::self()->restoreCallingIdentity(token);
1517
1518 // Reacquire mServiceLock
1519 mServiceLock.lock();
1520}
Ruben Brunkcc776712015-02-17 20:18:47 -08001521
Ruben Brunka8ca9152015-04-07 14:23:40 -07001522void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001523 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001524 Mutex::Autolock l(mLogLock);
1525 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526}
1527
Ruben Brunka8ca9152015-04-07 14:23:40 -07001528void CameraService::logDisconnected(const char* cameraId, int clientPid,
1529 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001530 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001531 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1532 clientPackage, clientPid));
1533}
1534
1535void CameraService::logConnected(const char* cameraId, int clientPid,
1536 const char* clientPackage) {
1537 // Log the clients evicted
1538 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1539 clientPackage, clientPid));
1540}
1541
1542void CameraService::logRejected(const char* cameraId, int clientPid,
1543 const char* clientPackage, const char* reason) {
1544 // Log the client rejected
1545 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1546 cameraId, clientPackage, clientPid, reason));
1547}
1548
1549void CameraService::logUserSwitch(int oldUserId, int newUserId) {
1550 // Log the new and old users
1551 logEvent(String8::format("USER_SWITCH from old user: %d , to new user: %d", oldUserId,
1552 newUserId));
1553}
1554
1555void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1556 // Log the device removal
1557 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1558}
1559
1560void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1561 // Log the device removal
1562 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1563}
1564
1565void CameraService::logClientDied(int clientPid, const char* reason) {
1566 // Log the device removal
1567 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001568}
1569
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001570void CameraService::logServiceError(const char* msg, int errorCode) {
1571 String8 curTime = getFormattedCurrentTime();
1572 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1573}
1574
Ruben Brunk36597b22015-03-20 22:15:57 -07001575status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1576 uint32_t flags) {
1577
1578 const int pid = getCallingPid();
1579 const int selfPid = getpid();
1580
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 // Permission checks
1582 switch (code) {
1583 case BnCameraService::CONNECT:
Eino-Ville Talvala63d877f2014-06-16 19:21:12 -07001584 case BnCameraService::CONNECT_DEVICE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001585 case BnCameraService::CONNECT_LEGACY: {
1586 if (pid != selfPid) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 // we're called from a different process, do the real check
1588 if (!checkCallingPermission(
1589 String16("android.permission.CAMERA"))) {
1590 const int uid = getCallingUid();
Steve Block29357bc2012-01-06 19:20:56 +00001591 ALOGE("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 "can't use the camera pid=%d, uid=%d", pid, uid);
1593 return PERMISSION_DENIED;
1594 }
1595 }
1596 break;
Ruben Brunk36597b22015-03-20 22:15:57 -07001597 }
1598 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1599 if (pid != selfPid) {
1600 // Ensure we're being called by system_server, or similar process with
1601 // permissions to notify the camera service about system events
1602 if (!checkCallingPermission(
1603 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1604 const int uid = getCallingUid();
1605 ALOGE("Permission Denial: cannot send updates to camera service about system"
1606 " events from pid=%d, uid=%d", pid, uid);
1607 return PERMISSION_DENIED;
1608 }
1609 }
1610 break;
1611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 }
1613
1614 return BnCameraService::onTransact(code, data, reply, flags);
1615}
1616
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617// We share the media players for shutter and recording sound for all clients.
1618// A reference count is kept to determine when we will actually release the
1619// media players.
1620
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001621MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001623 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001624 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 mp->prepare();
1626 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001627 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 return NULL;
1629 }
1630 return mp;
1631}
1632
1633void CameraService::loadSound() {
1634 Mutex::Autolock lock(mSoundLock);
1635 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1636 if (mSoundRef++) return;
1637
1638 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1639 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1640}
1641
1642void CameraService::releaseSound() {
1643 Mutex::Autolock lock(mSoundLock);
1644 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1645 if (--mSoundRef) return;
1646
1647 for (int i = 0; i < NUM_SOUNDS; i++) {
1648 if (mSoundPlayer[i] != 0) {
1649 mSoundPlayer[i]->disconnect();
1650 mSoundPlayer[i].clear();
1651 }
1652 }
1653}
1654
1655void CameraService::playSound(sound_kind kind) {
1656 LOG1("playSound(%d)", kind);
1657 Mutex::Autolock lock(mSoundLock);
1658 sp<MediaPlayer> player = mSoundPlayer[kind];
1659 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001660 player->seekTo(0);
1661 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 }
1663}
1664
1665// ----------------------------------------------------------------------------
1666
1667CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001668 const sp<ICameraClient>& cameraClient,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001669 const String16& clientPackageName,
1670 int cameraId, int cameraFacing,
1671 int clientPid, uid_t clientUid,
1672 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001673 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001674 IInterface::asBinder(cameraClient),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001675 clientPackageName,
1676 cameraId, cameraFacing,
1677 clientPid, clientUid,
1678 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001679{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001681 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001683 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001686
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001687 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688}
1689
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690// tear down the client
1691CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001692 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001693 mDestructionStarted = true;
1694
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001695 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001696 // unconditionally disconnect. function is idempotent
1697 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698}
1699
Igor Murashkin634a5152013-02-20 17:15:11 -08001700CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001701 const sp<IBinder>& remoteCallback,
1702 const String16& clientPackageName,
1703 int cameraId, int cameraFacing,
1704 int clientPid, uid_t clientUid,
1705 int servicePid):
Ruben Brunkcc776712015-02-17 20:18:47 -08001706 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001707{
1708 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001709 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001710 mCameraId = cameraId;
1711 mCameraFacing = cameraFacing;
1712 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001713 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001714 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001715 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001716 mDestructionStarted = false;
1717}
1718
1719CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001720 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001721 mDestructionStarted = true;
1722}
1723
1724void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001725 if (mDisconnected) {
1726 ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1727 mCameraId);
1728 return;
1729 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001730 mDisconnected = true;;
1731
1732 mCameraService->removeByClient(this);
1733 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
1734 String8(mClientPackageName));
1735
1736 sp<IBinder> remote = getRemote();
1737 if (remote != nullptr) {
1738 remote->unlinkToDeath(mCameraService);
1739 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001740
1741 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001742 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1743
Igor Murashkincba2c162013-03-20 15:56:31 -07001744 // client shouldn't be able to call into us anymore
1745 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001746}
1747
Ruben Brunkcc776712015-02-17 20:18:47 -08001748String16 CameraService::BasicClient::getPackageName() const {
1749 return mClientPackageName;
1750}
1751
1752
1753int CameraService::BasicClient::getClientPid() const {
1754 return mClientPid;
1755}
1756
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001757status_t CameraService::BasicClient::startCameraOps() {
1758 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001759 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001760 mOpsCallback = new OpsCallback(this);
1761
Igor Murashkine6800ce2013-03-04 17:25:57 -08001762 {
1763 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1764 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1765 }
1766
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001767 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1768 mClientPackageName, mOpsCallback);
1769 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1770 mClientUid, mClientPackageName);
1771
1772 if (res != AppOpsManager::MODE_ALLOWED) {
1773 ALOGI("Camera %d: Access for \"%s\" has been revoked",
1774 mCameraId, String8(mClientPackageName).string());
1775 return PERMISSION_DENIED;
1776 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001777
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001778 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001779
1780 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1781 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001782 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001783
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001784 return OK;
1785}
1786
1787status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001788 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001789 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001790 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001791 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1792 mClientPackageName);
1793 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001794
Ruben Brunkcc776712015-02-17 20:18:47 -08001795 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1796 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001797
Ruben Brunkcc776712015-02-17 20:18:47 -08001798 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001799 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001800 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001801
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001802 // Notify flashlight that a camera device is closed.
1803 mCameraService->mFlashlight->deviceClosed(
1804 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001805 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001806 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001807 if (mOpsCallback != NULL) {
1808 mAppOpsManager.stopWatchingMode(mOpsCallback);
1809 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001810 mOpsCallback.clear();
1811
1812 return OK;
1813}
1814
1815void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1816 String8 name(packageName);
1817 String8 myName(mClientPackageName);
1818
1819 if (op != AppOpsManager::OP_CAMERA) {
1820 ALOGW("Unexpected app ops notification received: %d", op);
1821 return;
1822 }
1823
1824 int32_t res;
1825 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1826 mClientUid, mClientPackageName);
1827 ALOGV("checkOp returns: %d, %s ", res,
1828 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1829 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1830 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1831 "UNKNOWN");
1832
1833 if (res != AppOpsManager::MODE_ALLOWED) {
1834 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1835 myName.string());
1836 // Reset the client PID to allow server-initiated disconnect,
1837 // and to prevent further calls by client.
1838 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07001839 CaptureResultExtras resultExtras; // a dummy result (invalid)
1840 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001841 disconnect();
1842 }
1843}
1844
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845// ----------------------------------------------------------------------------
1846
Ruben Brunkcc776712015-02-17 20:18:47 -08001847// Provide client strong pointer for callbacks.
1848sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
1849 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
1850 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
1851 if (clientDescriptor != nullptr) {
1852 return sp<Client>{
1853 static_cast<Client*>(clientDescriptor->getValue().get())};
1854 }
1855 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856}
1857
Jianing Weicb0652e2014-03-12 18:29:36 -07001858void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1859 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001860 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001861}
1862
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001863// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07001864void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001865 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08001866 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08001867}
1868
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001869CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1870 mClient(client) {
1871}
1872
1873void CameraService::Client::OpsCallback::opChanged(int32_t op,
1874 const String16& packageName) {
1875 sp<BasicClient> client = mClient.promote();
1876 if (client != NULL) {
1877 client->opChanged(op, packageName);
1878 }
1879}
1880
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08001882// CameraState
1883// ----------------------------------------------------------------------------
1884
1885CameraService::CameraState::CameraState(const String8& id, int cost,
1886 const std::set<String8>& conflicting) : mId(id),
1887 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
1888
1889CameraService::CameraState::~CameraState() {}
1890
1891ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
1892 Mutex::Autolock lock(mStatusLock);
1893 return mStatus;
1894}
1895
1896CameraParameters CameraService::CameraState::getShimParams() const {
1897 return mShimParams;
1898}
1899
1900void CameraService::CameraState::setShimParams(const CameraParameters& params) {
1901 mShimParams = params;
1902}
1903
1904int CameraService::CameraState::getCost() const {
1905 return mCost;
1906}
1907
1908std::set<String8> CameraService::CameraState::getConflicting() const {
1909 return mConflicting;
1910}
1911
1912String8 CameraService::CameraState::getId() const {
1913 return mId;
1914}
1915
1916// ----------------------------------------------------------------------------
1917// CameraClientManager
1918// ----------------------------------------------------------------------------
1919
1920CameraService::CameraClientManager::~CameraClientManager() {}
1921
1922sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
1923 const String8& id) const {
1924 auto descriptor = get(id);
1925 if (descriptor == nullptr) {
1926 return sp<BasicClient>{nullptr};
1927 }
1928 return descriptor->getValue();
1929}
1930
1931String8 CameraService::CameraClientManager::toString() const {
1932 auto all = getAll();
1933 String8 ret("[");
1934 bool hasAny = false;
1935 for (auto& i : all) {
1936 hasAny = true;
1937 String8 key = i->getKey();
1938 int32_t cost = i->getCost();
1939 int32_t pid = i->getOwnerId();
1940 int32_t priority = i->getPriority();
1941 auto conflicting = i->getConflicting();
1942 auto clientSp = i->getValue();
1943 String8 packageName;
1944 if (clientSp.get() != nullptr) {
1945 packageName = String8{clientSp->getPackageName()};
1946 }
1947 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
1948 PRId32 ", ", key.string(), cost, pid, priority);
1949
1950 if (packageName.size() != 0) {
1951 ret.appendFormat("Client Package Name: %s", packageName.string());
1952 }
1953
1954 ret.append(", Conflicting Client Devices: {");
1955 for (auto& j : conflicting) {
1956 ret.appendFormat("%s, ", j.string());
1957 }
1958 ret.append("})");
1959 }
1960 if (hasAny) ret.append("\n");
1961 ret.append("]\n");
1962 return ret;
1963}
1964
1965CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1966 const String8& key, const sp<BasicClient>& value, int32_t cost,
1967 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
1968
1969 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
1970 key, value, cost, conflictingKeys, priority, ownerId);
1971}
1972
1973CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1974 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
1975 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
1976 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
1977}
1978
1979// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980
1981static const int kDumpLockRetries = 50;
1982static const int kDumpLockSleep = 60000;
1983
1984static bool tryLock(Mutex& mutex)
1985{
1986 bool locked = false;
1987 for (int i = 0; i < kDumpLockRetries; ++i) {
1988 if (mutex.tryLock() == NO_ERROR) {
1989 locked = true;
1990 break;
1991 }
1992 usleep(kDumpLockSleep);
1993 }
1994 return locked;
1995}
1996
1997status_t CameraService::dump(int fd, const Vector<String16>& args) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001998 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002000 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 "can't dump CameraService from pid=%d, uid=%d\n",
2002 getCallingPid(),
2003 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 write(fd, result.string(), result.size());
2005 } else {
2006 bool locked = tryLock(mServiceLock);
2007 // failed to lock - CameraService is probably deadlocked
2008 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002009 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002010 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 }
2012
2013 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002014 if (!mModule) {
2015 result = String8::format("No camera module available!\n");
2016 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002017
2018 // Dump event log for error information
2019 dumpEventLog(fd);
2020
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002021 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002022 return NO_ERROR;
2023 }
2024
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002025 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2026 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2027 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2028 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002029 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2030 String8 activeClientString = mActiveClientManager.toString();
2031 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2032
Ruben Brunkf81648e2014-04-17 16:14:57 -07002033 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2034 if (desc == NULL) {
2035 result.appendFormat("Vendor tags left unimplemented.\n");
2036 } else {
2037 result.appendFormat("Vendor tag definitions:\n");
2038 }
2039
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002040 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002041
2042 if (desc != NULL) {
2043 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2044 }
2045
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002046 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002047
2048 bool stateLocked = tryLock(mCameraStatesLock);
2049 if (!stateLocked) {
2050 result = String8::format("CameraStates in use, may be deadlocked\n");
2051 write(fd, result.string(), result.size());
2052 }
2053
2054 for (auto& state : mCameraStates) {
2055 String8 cameraId = state.first;
2056 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002057 camera_info info;
2058
Ruben Brunkcc776712015-02-17 20:18:47 -08002059 // TODO: Change getCameraInfo + HAL to use String cameraIds
2060 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002061 if (rc != OK) {
2062 result.appendFormat(" Error reading static information!\n");
2063 write(fd, result.string(), result.size());
2064 } else {
2065 result.appendFormat(" Facing: %s\n",
2066 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2067 result.appendFormat(" Orientation: %d\n", info.orientation);
2068 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002069 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002070 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2071 } else {
2072 deviceVersion = info.device_version;
2073 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002074
2075 auto conflicting = state.second->getConflicting();
2076 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2077 result.appendFormat(" Conflicting Devices:");
2078 for (auto& id : conflicting) {
2079 result.appendFormat(" %s", cameraId.string());
2080 }
2081 if (conflicting.size() == 0) {
2082 result.appendFormat(" NONE");
2083 }
2084 result.appendFormat("\n");
2085
2086 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002087 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2088 result.appendFormat(" Device static metadata:\n");
2089 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002090 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002091 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002092 } else {
2093 write(fd, result.string(), result.size());
2094 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002095
2096 CameraParameters p = state.second->getShimParams();
2097 if (!p.isEmpty()) {
2098 result = String8::format(" Camera1 API shim is using parameters:\n ");
2099 write(fd, result.string(), result.size());
2100 p.dump(fd, args);
2101 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002102 }
2103
Ruben Brunkcc776712015-02-17 20:18:47 -08002104 auto clientDescriptor = mActiveClientManager.get(cameraId);
2105 if (clientDescriptor == nullptr) {
2106 result = String8::format(" Device %s is closed, no client instance\n",
2107 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002108 write(fd, result.string(), result.size());
2109 continue;
2110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002112 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2113 cameraId.string());
2114 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2115 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2116
2117 auto client = clientDescriptor->getValue();
2118 result.appendFormat("Client package: %s\n",
2119 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002120 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002121
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002122 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002124
2125 if (stateLocked) mCameraStatesLock.unlock();
2126
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002128 result = String8::format("\nNo active camera clients yet.\n");
2129 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 }
2131
2132 if (locked) mServiceLock.unlock();
2133
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002134 // Dump camera traces if there were any
2135 write(fd, "\n", 1);
2136 camera3::CameraTraces::dump(fd, args);
2137
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 // change logging level
2139 int n = args.size();
2140 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002141 String16 verboseOption("-v");
2142 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 String8 levelStr(args[i+1]);
2144 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002145 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002147 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 }
2149 }
2150 }
2151 return NO_ERROR;
2152}
2153
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002154void CameraService::dumpEventLog(int fd) {
2155 String8 result = String8("\nPrior client events (most recent at top):\n");
2156
2157 Mutex::Autolock l(mLogLock);
2158 for (const auto& msg : mEventLog) {
2159 result.appendFormat(" %s\n", msg.string());
2160 }
2161
2162 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2163 result.append(" ...\n");
2164 } else if (mEventLog.size() == 0) {
2165 result.append(" [no events yet]\n");
2166 }
2167 result.append("\n");
2168
2169 write(fd, result.string(), result.size());
2170}
2171
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002172void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002173 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002174 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2175 if (mTorchClientMap[i] == who) {
2176 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002177 String8 cameraId = mTorchClientMap.keyAt(i);
2178 status_t res = mFlashlight->setTorchMode(cameraId, false);
2179 if (res) {
2180 ALOGE("%s: torch client died but couldn't turn off torch: "
2181 "%s (%d)", __FUNCTION__, strerror(-res), res);
2182 return;
2183 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002184 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002185 break;
2186 }
2187 }
2188}
2189
Ruben Brunkcc776712015-02-17 20:18:47 -08002190/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002191
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002192 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002193 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2194 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002195 */
2196
Ruben Brunka8ca9152015-04-07 14:23:40 -07002197 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2198
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002199 // check torch client
2200 handleTorchClientBinderDied(who);
2201
2202 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002203 if(!evictClientIdByRemote(who)) {
2204 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002205 return;
2206 }
2207
Ruben Brunkcc776712015-02-17 20:18:47 -08002208 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2209 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002210}
2211
Ruben Brunkcc776712015-02-17 20:18:47 -08002212void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2213 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002214}
2215
Ruben Brunkcc776712015-02-17 20:18:47 -08002216void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2217 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2218 // Do not lock mServiceLock here or can get into a deadlock from
2219 // connect() -> disconnect -> updateStatus
2220
2221 auto state = getCameraState(cameraId);
2222
2223 if (state == nullptr) {
2224 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2225 cameraId.string());
2226 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002227 }
2228
Ruben Brunkcc776712015-02-17 20:18:47 -08002229 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2230 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2231 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2232 (const String8& cameraId, ICameraServiceListener::Status status) {
2233
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002234 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2235 // Update torch status if it has a flash unit.
2236 Mutex::Autolock al(mTorchStatusMutex);
2237 ICameraServiceListener::TorchStatus torchStatus;
2238 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2239 NAME_NOT_FOUND) {
2240 ICameraServiceListener::TorchStatus newTorchStatus =
2241 status == ICameraServiceListener::STATUS_PRESENT ?
2242 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2243 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2244 if (torchStatus != newTorchStatus) {
2245 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2246 }
2247 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002248 }
2249
2250 Mutex::Autolock lock(mStatusListenerLock);
2251
2252 for (auto& listener : mListenerList) {
2253 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2254 int id = cameraIdToInt(cameraId);
2255 if (id != -1) listener->onStatusChanged(status, id);
2256 }
2257 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002258}
2259
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002260status_t CameraService::getTorchStatusLocked(
2261 const String8& cameraId,
2262 ICameraServiceListener::TorchStatus *status) const {
2263 if (!status) {
2264 return BAD_VALUE;
2265 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002266 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2267 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002268 // invalid camera ID or the camera doesn't have a flash unit
2269 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002270 }
2271
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002272 *status = mTorchStatusMap.valueAt(index);
2273 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002274}
2275
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002276status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002277 ICameraServiceListener::TorchStatus status) {
2278 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2279 if (index == NAME_NOT_FOUND) {
2280 return BAD_VALUE;
2281 }
2282 ICameraServiceListener::TorchStatus& item =
2283 mTorchStatusMap.editValueAt(index);
2284 item = status;
2285
2286 return OK;
2287}
2288
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289}; // namespace android