blob: 67a1d5dfa11123a43ea8323dbb8540b71f6d4603 [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) {
316 ALOGE("%s: cannot get torch status of camera %s", cameraId.string());
317 return;
318 }
319 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800320 ALOGE("%s: Torch state transition to the same status 0x%x not allowed",
321 __FUNCTION__, (uint32_t)newStatus);
322 return;
323 }
324
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800325 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800326 if (res) {
327 ALOGE("%s: Failed to set the torch status", __FUNCTION__,
328 (uint32_t)newStatus);
329 return;
330 }
331
Ruben Brunkcc776712015-02-17 20:18:47 -0800332 {
333 Mutex::Autolock lock(mStatusListenerLock);
334 for (auto& i : mListenerList) {
335 i->onTorchStatusChanged(newStatus, String16{cameraId});
336 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800337 }
338}
339
340
Mathias Agopian65ab4712010-07-14 17:59:35 -0700341int32_t CameraService::getNumberOfCameras() {
342 return mNumberOfCameras;
343}
344
345status_t CameraService::getCameraInfo(int cameraId,
346 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700347 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700348 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700349 }
350
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
352 return BAD_VALUE;
353 }
354
Iliyan Malchev8951a972011-04-14 16:55:59 -0700355 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700356 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800357 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700358 cameraInfo->facing = info.facing;
359 cameraInfo->orientation = info.orientation;
360 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361}
362
Ruben Brunkcc776712015-02-17 20:18:47 -0800363int CameraService::cameraIdToInt(const String8& cameraId) {
364 errno = 0;
365 size_t pos = 0;
366 int ret = stoi(std::string{cameraId.string()}, &pos);
367 if (errno != 0 || pos != cameraId.size()) {
368 return -1;
369 }
370 return ret;
371}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700372
373status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
374 status_t ret = OK;
375 struct CameraInfo info;
376 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
377 return ret;
378 }
379
380 CameraMetadata shimInfo;
381 int32_t orientation = static_cast<int32_t>(info.orientation);
382 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
383 return ret;
384 }
385
386 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
387 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
388 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
389 return ret;
390 }
391
Igor Murashkin65d14b92014-06-17 12:03:20 -0700392 CameraParameters shimParams;
393 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
394 // Error logged by callee
395 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700396 }
397
398 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700399 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700400 Vector<int32_t> formats;
401 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700402 {
403 shimParams.getSupportedPreviewSizes(/*out*/sizes);
404 shimParams.getSupportedPreviewFormats(/*out*/formats);
405 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700406 }
407
408 // Always include IMPLEMENTATION_DEFINED
409 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
410
411 const size_t INTS_PER_CONFIG = 4;
412
413 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700414 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
415
416 Vector<int32_t> streamConfigs;
417 streamConfigs.setCapacity(streamConfigSize);
418
Ruben Brunkb2119af2014-05-09 19:57:56 -0700419 for (size_t i = 0; i < formats.size(); ++i) {
420 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700421 streamConfigs.add(formats[i]);
422 streamConfigs.add(sizes[j].width);
423 streamConfigs.add(sizes[j].height);
424 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700425 }
426 }
427
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700428 for (size_t i = 0; i < jpegSizes.size(); ++i) {
429 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
430 streamConfigs.add(jpegSizes[i].width);
431 streamConfigs.add(jpegSizes[i].height);
432 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
433 }
434
Ruben Brunkb2119af2014-05-09 19:57:56 -0700435 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700436 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700437 return ret;
438 }
439
440 int64_t fakeMinFrames[0];
441 // TODO: Fixme, don't fake min frame durations.
442 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
443 fakeMinFrames, 0)) != OK) {
444 return ret;
445 }
446
447 int64_t fakeStalls[0];
448 // TODO: Fixme, don't fake stall durations.
449 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
450 fakeStalls, 0)) != OK) {
451 return ret;
452 }
453
454 *cameraInfo = shimInfo;
455 return OK;
456}
457
Zhijun He2b59be82013-09-25 10:14:30 -0700458status_t CameraService::getCameraCharacteristics(int cameraId,
459 CameraMetadata* cameraInfo) {
460 if (!cameraInfo) {
461 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
462 return BAD_VALUE;
463 }
464
465 if (!mModule) {
466 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
467 return -ENODEV;
468 }
469
Zhijun He2b59be82013-09-25 10:14:30 -0700470 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
471 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
472 return BAD_VALUE;
473 }
474
475 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700476 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800477 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700478 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
479 /**
480 * Backwards compatibility mode for old HALs:
481 * - Convert CameraInfo into static CameraMetadata properties.
482 * - Retrieve cached CameraParameters for this camera. If none exist,
483 * attempt to open CameraClient and retrieve the CameraParameters.
484 * - Convert cached CameraParameters into static CameraMetadata
485 * properties.
486 */
487 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700488
Ruben Brunkb2119af2014-05-09 19:57:56 -0700489 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
490 return ret;
491 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700492
Ruben Brunkb2119af2014-05-09 19:57:56 -0700493 } else {
494 /**
495 * Normal HAL 2.1+ codepath.
496 */
497 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800498 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700499 *cameraInfo = info.static_camera_characteristics;
500 }
Zhijun He2b59be82013-09-25 10:14:30 -0700501
502 return ret;
503}
504
Ruben Brunkcc776712015-02-17 20:18:47 -0800505int CameraService::getCallingPid() {
506 return IPCThreadState::self()->getCallingPid();
507}
508
509int CameraService::getCallingUid() {
510 return IPCThreadState::self()->getCallingUid();
511}
512
513String8 CameraService::getFormattedCurrentTime() {
514 time_t now = time(nullptr);
515 char formattedTime[64];
516 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
517 return String8(formattedTime);
518}
519
520int CameraService::getCameraPriorityFromProcState(int procState) {
521 // Find the priority for the camera usage based on the process state. Higher priority clients
522 // win for evictions.
523 // Note: Unlike the ordering for ActivityManager, persistent system processes will always lose
524 // the camera to the top/foreground applications.
525 switch(procState) {
526 case PROCESS_STATE_TOP: // User visible
527 return 100;
528 case PROCESS_STATE_IMPORTANT_FOREGROUND: // Foreground
529 return 90;
530 case PROCESS_STATE_PERSISTENT: // Persistent system services
531 case PROCESS_STATE_PERSISTENT_UI:
532 return 80;
533 case PROCESS_STATE_IMPORTANT_BACKGROUND: // "Important" background processes
534 return 70;
535 case PROCESS_STATE_BACKUP: // Everything else
536 case PROCESS_STATE_HEAVY_WEIGHT:
537 case PROCESS_STATE_SERVICE:
538 case PROCESS_STATE_RECEIVER:
539 case PROCESS_STATE_HOME:
540 case PROCESS_STATE_LAST_ACTIVITY:
541 case PROCESS_STATE_CACHED_ACTIVITY:
542 case PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
543 case PROCESS_STATE_CACHED_EMPTY:
544 return 1;
545 case PROCESS_STATE_NONEXISTENT:
546 return -1;
547 default:
548 ALOGE("%s: Received unknown process state from ActivityManagerService!", __FUNCTION__);
549 return -1;
550 }
551}
552
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800553status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
554 if (!mModule) {
555 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
556 return -ENODEV;
557 }
558
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800559 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
560 return OK;
561}
562
Igor Murashkin634a5152013-02-20 17:15:11 -0800563int CameraService::getDeviceVersion(int cameraId, int* facing) {
564 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800565 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800566 return -1;
567 }
568
569 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800570 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800571 deviceVersion = info.device_version;
572 } else {
573 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
574 }
575
576 if (facing) {
577 *facing = info.facing;
578 }
579
580 return deviceVersion;
581}
582
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700583status_t CameraService::filterGetInfoErrorCode(status_t err) {
584 switch(err) {
585 case NO_ERROR:
586 case -EINVAL:
587 return err;
588 default:
589 break;
590 }
591 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800592}
593
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800594bool CameraService::setUpVendorTags() {
595 vendor_tag_ops_t vOps = vendor_tag_ops_t();
596
597 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800598 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800599 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
600 return false;
601 }
602
603 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800604 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800605 ATRACE_END();
606
607 // Ensure all vendor operations are present
608 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
609 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
610 vOps.get_tag_type == NULL) {
611 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
612 , __FUNCTION__);
613 return false;
614 }
615
616 // Read all vendor tag definitions into a descriptor
617 sp<VendorTagDescriptor> desc;
618 status_t res;
619 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
620 != OK) {
621 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
622 "received error %s (%d). Camera clients will not be able to use"
623 "vendor tags", __FUNCTION__, strerror(res), res);
624 return false;
625 }
626
627 // Set the global descriptor to use with camera metadata
628 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
629 return true;
630}
631
Ruben Brunkcc776712015-02-17 20:18:47 -0800632status_t CameraService::makeClient(const sp<CameraService>& cameraService,
633 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
634 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
635 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
636 /*out*/sp<BasicClient>* client) {
637
638 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
639 int id = cameraIdToInt(cameraId);
640 if (id == -1) {
641 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
642 cameraId.string());
643 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700644 }
645
Ruben Brunkcc776712015-02-17 20:18:47 -0800646 if (halVersion < 0 || halVersion == deviceVersion) {
647 // Default path: HAL version is unspecified by caller, create CameraClient
648 // based on device version reported by the HAL.
649 switch(deviceVersion) {
650 case CAMERA_DEVICE_API_VERSION_1_0:
651 if (effectiveApiLevel == API_1) { // Camera1 API route
652 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
653 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
654 clientPid, clientUid, getpid(), legacyMode);
655 } else { // Camera2 API route
656 ALOGW("Camera using old HAL version: %d", deviceVersion);
657 return -EOPNOTSUPP;
658 }
659 break;
660 case CAMERA_DEVICE_API_VERSION_2_0:
661 case CAMERA_DEVICE_API_VERSION_2_1:
662 case CAMERA_DEVICE_API_VERSION_3_0:
663 case CAMERA_DEVICE_API_VERSION_3_1:
664 case CAMERA_DEVICE_API_VERSION_3_2:
665 case CAMERA_DEVICE_API_VERSION_3_3:
666 if (effectiveApiLevel == API_1) { // Camera1 API route
667 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
668 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
669 clientPid, clientUid, servicePid, legacyMode);
670 } else { // Camera2 API route
671 sp<ICameraDeviceCallbacks> tmp =
672 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
673 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
674 facing, clientPid, clientUid, servicePid);
675 }
676 break;
677 default:
678 // Should not be reachable
679 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
680 return INVALID_OPERATION;
681 }
682 } else {
683 // A particular HAL version is requested by caller. Create CameraClient
684 // based on the requested HAL version.
685 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
686 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
687 // Only support higher HAL version device opened as HAL1.0 device.
688 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
689 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
690 clientPid, clientUid, servicePid, legacyMode);
691 } else {
692 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
693 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
694 " opened as HAL %x device", halVersion, deviceVersion,
695 CAMERA_DEVICE_API_VERSION_1_0);
696 return INVALID_OPERATION;
697 }
698 }
699 return NO_ERROR;
700}
701
702status_t CameraService::initializeShimMetadata(int cameraId) {
703 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700704
705 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800706 String8 id = String8::format("%d", cameraId);
707 status_t ret = NO_ERROR;
708 sp<Client> tmp = nullptr;
709 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
710 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
711 false, true, tmp)) != NO_ERROR) {
712 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
713 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700714 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800715 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700716}
717
Igor Murashkin65d14b92014-06-17 12:03:20 -0700718status_t CameraService::getLegacyParametersLazy(int cameraId,
719 /*out*/
720 CameraParameters* parameters) {
721
722 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
723
724 status_t ret = 0;
725
726 if (parameters == NULL) {
727 ALOGE("%s: parameters must not be null", __FUNCTION__);
728 return BAD_VALUE;
729 }
730
Ruben Brunkcc776712015-02-17 20:18:47 -0800731 String8 id = String8::format("%d", cameraId);
732
733 // Check if we already have parameters
734 {
735 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700736 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800737 auto cameraState = getCameraState(id);
738 if (cameraState == nullptr) {
739 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
740 return BAD_VALUE;
741 }
742 CameraParameters p = cameraState->getShimParams();
743 if (!p.isEmpty()) {
744 *parameters = p;
745 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700746 }
747 }
748
Ruben Brunkcc776712015-02-17 20:18:47 -0800749 int64_t token = IPCThreadState::self()->clearCallingIdentity();
750 ret = initializeShimMetadata(cameraId);
751 IPCThreadState::self()->restoreCallingIdentity(token);
752 if (ret != NO_ERROR) {
753 // Error already logged by callee
754 return ret;
755 }
756
757 // Check for parameters again
758 {
759 // Scope for service lock
760 Mutex::Autolock lock(mServiceLock);
761 auto cameraState = getCameraState(id);
762 if (cameraState == nullptr) {
763 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
764 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700765 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800766 CameraParameters p = cameraState->getShimParams();
767 if (!p.isEmpty()) {
768 *parameters = p;
769 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700770 }
771 }
772
Ruben Brunkcc776712015-02-17 20:18:47 -0800773 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
774 __FUNCTION__);
775 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700776}
777
Ruben Brunk36597b22015-03-20 22:15:57 -0700778status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
779 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800780
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500782
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800783 if (clientUid == USE_CALLING_UID) {
784 clientUid = getCallingUid();
785 } else {
786 // We only trust our own process to forward client UIDs
787 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700788 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
789 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700790 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800791 }
792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793
Iliyan Malchev8951a972011-04-14 16:55:59 -0700794 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800795 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
796 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700797 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700798 }
799
Ruben Brunkcc776712015-02-17 20:18:47 -0800800 if (getCameraState(cameraId) == nullptr) {
801 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
802 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700803 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805
Ruben Brunkcc776712015-02-17 20:18:47 -0800806 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800807 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800808 char key[PROPERTY_KEY_MAX];
809 int clientUserId = multiuser_get_user_id(clientUid);
810 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
811 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800812 if (strcmp(value, "1") == 0) {
813 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
815 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700816 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800817 }
818
Ruben Brunka8ca9152015-04-07 14:23:40 -0700819 // Only allow clients who are being used by the current foreground device user, unless calling
820 // from our own process.
821 if (callingPid != getpid() &&
822 (mLastUserId != clientUserId && mLastUserId != DEFAULT_LAST_USER_ID)) {
823 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from previous "
824 "device user %d, current device user %d)", callingPid, clientUserId, mLastUserId);
Ruben Brunk36597b22015-03-20 22:15:57 -0700825 return PERMISSION_DENIED;
826 }
827
Ruben Brunkcc776712015-02-17 20:18:47 -0800828 return checkIfDeviceIsUsable(cameraId);
829}
830
831status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
832 auto cameraState = getCameraState(cameraId);
833 int callingPid = getCallingPid();
834 if (cameraState == nullptr) {
835 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
836 cameraId.string());
837 return -ENODEV;
838 }
839
840 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700841 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800842 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
843 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700844 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700845 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800846 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
847 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700848 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700849 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700850
Ruben Brunkcc776712015-02-17 20:18:47 -0800851 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800852}
853
Ruben Brunkcc776712015-02-17 20:18:47 -0800854void CameraService::finishConnectLocked(const sp<BasicClient>& client,
855 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800856
Ruben Brunkcc776712015-02-17 20:18:47 -0800857 // Make a descriptor for the incoming client
858 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
859 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
860
861 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
862 String8(client->getPackageName()));
863
864 if (evicted.size() > 0) {
865 // This should never happen - clients should already have been removed in disconnect
866 for (auto& i : evicted) {
867 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
868 __FUNCTION__, i->getKey().string());
869 }
870
871 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
872 __FUNCTION__);
873 }
874}
875
876status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
877 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
878 /*out*/
879 sp<BasicClient>* client,
880 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
881
882 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700883 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800884 DescriptorPtr clientDescriptor;
885 {
886 if (effectiveApiLevel == API_1) {
887 // If we are using API1, any existing client for this camera ID with the same remote
888 // should be returned rather than evicted to allow MediaRecorder to work properly.
889
890 auto current = mActiveClientManager.get(cameraId);
891 if (current != nullptr) {
892 auto clientSp = current->getValue();
893 if (clientSp.get() != nullptr) { // should never be needed
894 if (clientSp->getRemote() == remoteCallback) {
895 ALOGI("CameraService::connect X (PID %d) (second call from same"
896 "app binder, returning the same client)", clientPid);
897 *client = clientSp;
898 return NO_ERROR;
899 }
900 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800901 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800902 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800903
Ruben Brunkcc776712015-02-17 20:18:47 -0800904 // Return error if the device was unplugged or removed by the HAL for some reason
905 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
906 return ret;
907 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800908
Ruben Brunkcc776712015-02-17 20:18:47 -0800909 // Get current active client PIDs
910 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
911 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800912
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700913 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
914 // address of PROCESS_STATE_NONEXISTENT as a reference argument
915 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
916 // not have an out-of-class definition.
917 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800918
Ruben Brunkcc776712015-02-17 20:18:47 -0800919 // Get priorites of all active PIDs
920 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
921 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700922
Ruben Brunkcc776712015-02-17 20:18:47 -0800923 // Update all active clients' priorities
924 std::map<int,int> pidToPriorityMap;
925 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
926 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
927 }
928 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800929
Ruben Brunkcc776712015-02-17 20:18:47 -0800930 // Get state for the given cameraId
931 auto state = getCameraState(cameraId);
932 if (state == nullptr) {
933 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
934 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700935 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -0700936 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800937
938 // Make descriptor for incoming client
939 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
940 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
941 state->getConflicting(),
942 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
943
944 // Find clients that would be evicted
945 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
946
947 // If the incoming client was 'evicted,' higher priority clients have the camera in the
948 // background, so we cannot do evictions
949 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
950 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
951 " priority).", clientPid);
952
953 sp<BasicClient> clientSp = clientDescriptor->getValue();
954 String8 curTime = getFormattedCurrentTime();
955 auto incompatibleClients =
956 mActiveClientManager.getIncompatibleClients(clientDescriptor);
957
958 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -0700959 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800960 cameraId.string(), packageName.string(), clientPid,
961 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
962
963 for (auto& i : incompatibleClients) {
964 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
965 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
966 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
967 i->getPriority());
968 }
969
970 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -0700971 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800972 mEventLog.add(msg);
973
974 return -EBUSY;
975 }
976
977 for (auto& i : evicted) {
978 sp<BasicClient> clientSp = i->getValue();
979 if (clientSp.get() == nullptr) {
980 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
981
982 // TODO: Remove this
983 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
984 __FUNCTION__);
985 mActiveClientManager.remove(i);
986 continue;
987 }
988
989 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
990 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700991 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -0800992
Ruben Brunkcc776712015-02-17 20:18:47 -0800993 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -0700994 logEvent(String8::format("EVICT device %s client held by package %s (PID"
995 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
996 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -0800997 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
998 i->getOwnerId(), i->getPriority(), cameraId.string(),
999 packageName.string(), clientPid,
1000 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1001
1002 // Notify the client of disconnection
1003 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1004 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001005 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001006 }
1007
Ruben Brunkcc776712015-02-17 20:18:47 -08001008 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1009 // other clients from connecting in mServiceLockWrapper if held
1010 mServiceLock.unlock();
1011
1012 // Clear caller identity temporarily so client disconnect PID checks work correctly
1013 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1014
1015 // Destroy evicted clients
1016 for (auto& i : evictedClients) {
1017 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001018 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001020
1021 IPCThreadState::self()->restoreCallingIdentity(token);
1022
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001023 for (const auto& i : evictedClients) {
1024 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1025 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1026 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1027 if (ret == TIMED_OUT) {
1028 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1029 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1030 mActiveClientManager.toString().string());
1031 return -EBUSY;
1032 }
1033 if (ret != NO_ERROR) {
1034 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1035 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1036 ret, mActiveClientManager.toString().string());
1037 return ret;
1038 }
1039 }
1040
1041 evictedClients.clear();
1042
Ruben Brunkcc776712015-02-17 20:18:47 -08001043 // Once clients have been disconnected, relock
1044 mServiceLock.lock();
1045
1046 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1047 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1048 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001049 }
1050
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 *partial = clientDescriptor;
1052 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001053}
1054
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001055status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001056 const sp<ICameraClient>& cameraClient,
1057 int cameraId,
1058 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001059 int clientUid,
1060 /*out*/
1061 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001062
Ruben Brunkcc776712015-02-17 20:18:47 -08001063 status_t ret = NO_ERROR;
1064 String8 id = String8::format("%d", cameraId);
1065 sp<Client> client = nullptr;
1066 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
1067 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001068
Ruben Brunkcc776712015-02-17 20:18:47 -08001069 if(ret != NO_ERROR) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001070 logRejected(id, getCallingPid(), String8(clientPackageName),
1071 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001072 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 }
1074
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001075 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001076 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077}
1078
Zhijun Heb10cdad2014-06-16 16:38:35 -07001079status_t CameraService::connectLegacy(
1080 const sp<ICameraClient>& cameraClient,
1081 int cameraId, int halVersion,
1082 const String16& clientPackageName,
1083 int clientUid,
1084 /*out*/
1085 sp<ICamera>& device) {
1086
Ruben Brunka8ca9152015-04-07 14:23:40 -07001087 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001088 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001089 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001090 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001091 /*
1092 * Either the HAL version is unspecified in which case this just creates
1093 * a camera client selected by the latest device version, or
1094 * it's a particular version in which case the HAL must supported
1095 * the open_legacy call
1096 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001097 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001098 __FUNCTION__, apiVersion);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001099 logRejected(id, getCallingPid(), String8(clientPackageName),
1100 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001101 return INVALID_OPERATION;
1102 }
1103
Ruben Brunkcc776712015-02-17 20:18:47 -08001104 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001105 sp<Client> client = nullptr;
1106 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
1107 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001108
Ruben Brunkcc776712015-02-17 20:18:47 -08001109 if(ret != NO_ERROR) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001110 logRejected(id, getCallingPid(), String8(clientPackageName),
1111 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001112 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001113 }
1114
Zhijun Heb10cdad2014-06-16 16:38:35 -07001115 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001116 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001117}
1118
Ruben Brunkcc776712015-02-17 20:18:47 -08001119status_t CameraService::connectDevice(
1120 const sp<ICameraDeviceCallbacks>& cameraCb,
1121 int cameraId,
1122 const String16& clientPackageName,
1123 int clientUid,
1124 /*out*/
1125 sp<ICameraDeviceUser>& device) {
1126
1127 status_t ret = NO_ERROR;
1128 String8 id = String8::format("%d", cameraId);
1129 sp<CameraDeviceClient> client = nullptr;
1130 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1131 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
1132 /*out*/client);
1133
1134 if(ret != NO_ERROR) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001135 logRejected(id, getCallingPid(), String8(clientPackageName),
1136 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001137 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001138 }
1139
Ruben Brunkcc776712015-02-17 20:18:47 -08001140 device = client;
1141 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001142}
1143
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001144status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1145 const sp<IBinder>& clientBinder) {
1146 if (enabled && clientBinder == NULL) {
1147 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001148 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001149 }
1150
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001151 String8 id = String8(cameraId.string());
1152
1153 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001154 auto state = getCameraState(id);
1155 if (state == nullptr) {
1156 ALOGE("%s: camera id is invalid %s", id.string());
1157 return -EINVAL;
1158 }
1159
1160 ICameraServiceListener::Status cameraStatus = state->getStatus();
1161 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1162 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001163 ALOGE("%s: camera id is invalid %s", id.string());
1164 return -EINVAL;
1165 }
1166
1167 {
1168 Mutex::Autolock al(mTorchStatusMutex);
1169 ICameraServiceListener::TorchStatus status;
1170 status_t res = getTorchStatusLocked(id, &status);
1171 if (res) {
1172 ALOGE("%s: getting current torch status failed for camera %s",
1173 __FUNCTION__, id.string());
1174 return -EINVAL;
1175 }
1176
1177 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001179 ALOGE("%s: torch mode of camera %s is not available because "
1180 "camera is in use", __FUNCTION__, id.string());
1181 return -EBUSY;
1182 } else {
1183 ALOGE("%s: torch mode of camera %s is not available due to "
1184 "insufficient resources", __FUNCTION__, id.string());
1185 return -EUSERS;
1186 }
1187 }
1188 }
1189
1190 status_t res = mFlashlight->setTorchMode(id, enabled);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001191 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001192 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1193 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001194 return res;
1195 }
1196
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001197 {
1198 // update the link to client's death
1199 Mutex::Autolock al(mTorchClientMapMutex);
1200 ssize_t index = mTorchClientMap.indexOfKey(id);
1201 if (enabled) {
1202 if (index == NAME_NOT_FOUND) {
1203 mTorchClientMap.add(id, clientBinder);
1204 } else {
1205 const sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
1206 oldBinder->unlinkToDeath(this);
1207
1208 mTorchClientMap.replaceValueAt(index, clientBinder);
1209 }
1210 clientBinder->linkToDeath(this);
1211 } else if (index != NAME_NOT_FOUND) {
1212 sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001213 oldBinder->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001214 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001215 }
1216
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001217 return OK;
1218}
1219
Ruben Brunk36597b22015-03-20 22:15:57 -07001220void CameraService::notifySystemEvent(int eventId, int arg0) {
1221 switch(eventId) {
1222 case ICameraService::USER_SWITCHED: {
1223 doUserSwitch(/*newUserId*/arg0);
1224 break;
1225 }
1226 case ICameraService::NO_EVENT:
1227 default: {
1228 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1229 eventId);
1230 break;
1231 }
1232 }
1233}
1234
Igor Murashkinbfc99152013-02-27 12:55:20 -08001235status_t CameraService::addListener(
1236 const sp<ICameraServiceListener>& listener) {
1237 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001238
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001239 if (listener == 0) {
1240 ALOGE("%s: Listener must not be null", __FUNCTION__);
1241 return BAD_VALUE;
1242 }
1243
Igor Murashkinbfc99152013-02-27 12:55:20 -08001244 Mutex::Autolock lock(mServiceLock);
1245
Ruben Brunkcc776712015-02-17 20:18:47 -08001246 {
1247 Mutex::Autolock lock(mStatusListenerLock);
1248 for (auto& it : mListenerList) {
1249 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1250 ALOGW("%s: Tried to add listener %p which was already subscribed",
1251 __FUNCTION__, listener.get());
1252 return ALREADY_EXISTS;
1253 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001254 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001255
1256 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001257 }
1258
Igor Murashkinbfc99152013-02-27 12:55:20 -08001259
Igor Murashkincba2c162013-03-20 15:56:31 -07001260 /* Immediately signal current status to this listener only */
1261 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001262 Mutex::Autolock lock(mCameraStatesLock);
1263 for (auto& i : mCameraStates) {
1264 // TODO: Update binder to use String16 for camera IDs and remove;
1265 int id = cameraIdToInt(i.first);
1266 if (id == -1) continue;
1267
1268 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001269 }
1270 }
1271
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001272 /* Immediately signal current torch status to this listener only */
1273 {
1274 Mutex::Autolock al(mTorchStatusMutex);
1275 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001276 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1277 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001278 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001279 }
1280
Igor Murashkinbfc99152013-02-27 12:55:20 -08001281 return OK;
1282}
Ruben Brunkcc776712015-02-17 20:18:47 -08001283
1284status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001285 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1286
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001287 if (listener == 0) {
1288 ALOGE("%s: Listener must not be null", __FUNCTION__);
1289 return BAD_VALUE;
1290 }
1291
Igor Murashkinbfc99152013-02-27 12:55:20 -08001292 Mutex::Autolock lock(mServiceLock);
1293
Ruben Brunkcc776712015-02-17 20:18:47 -08001294 {
1295 Mutex::Autolock lock(mStatusListenerLock);
1296 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1297 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1298 mListenerList.erase(it);
1299 return OK;
1300 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001301 }
1302 }
1303
1304 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1305 __FUNCTION__, listener.get());
1306
1307 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001308}
1309
Ruben Brunkcc776712015-02-17 20:18:47 -08001310status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001311 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1312
1313 if (parameters == NULL) {
1314 ALOGE("%s: parameters must not be null", __FUNCTION__);
1315 return BAD_VALUE;
1316 }
1317
1318 status_t ret = 0;
1319
1320 CameraParameters shimParams;
1321 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1322 // Error logged by caller
1323 return ret;
1324 }
1325
1326 String8 shimParamsString8 = shimParams.flatten();
1327 String16 shimParamsString16 = String16(shimParamsString8);
1328
1329 *parameters = shimParamsString16;
1330
1331 return OK;
1332}
1333
1334status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1335 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1336
1337 switch (apiVersion) {
1338 case API_VERSION_1:
1339 case API_VERSION_2:
1340 break;
1341 default:
1342 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1343 return BAD_VALUE;
1344 }
1345
1346 int facing = -1;
1347 int deviceVersion = getDeviceVersion(cameraId, &facing);
1348
1349 switch(deviceVersion) {
1350 case CAMERA_DEVICE_API_VERSION_1_0:
1351 case CAMERA_DEVICE_API_VERSION_2_0:
1352 case CAMERA_DEVICE_API_VERSION_2_1:
1353 case CAMERA_DEVICE_API_VERSION_3_0:
1354 case CAMERA_DEVICE_API_VERSION_3_1:
1355 if (apiVersion == API_VERSION_2) {
1356 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1357 __FUNCTION__, cameraId);
1358 return -EOPNOTSUPP;
1359 } else { // if (apiVersion == API_VERSION_1) {
1360 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1361 __FUNCTION__, cameraId);
1362 return OK;
1363 }
1364 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001365 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001366 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1367 __FUNCTION__, cameraId);
1368 return OK;
1369 case -1:
1370 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1371 return BAD_VALUE;
1372 default:
1373 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1374 return INVALID_OPERATION;
1375 }
1376
1377 return OK;
1378}
1379
Ruben Brunkcc776712015-02-17 20:18:47 -08001380void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001381 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001382 for (auto& i : mActiveClientManager.getAll()) {
1383 auto clientSp = i->getValue();
1384 if (clientSp.get() == client) {
1385 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001386 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001387 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001388}
1389
Ruben Brunkcc776712015-02-17 20:18:47 -08001390bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1391 const int callingPid = getCallingPid();
1392 const int servicePid = getpid();
1393 bool ret = false;
1394 {
1395 // Acquire mServiceLock and prevent other clients from connecting
1396 std::unique_ptr<AutoConditionLock> lock =
1397 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001398
Igor Murashkin634a5152013-02-20 17:15:11 -08001399
Ruben Brunkcc776712015-02-17 20:18:47 -08001400 std::vector<sp<BasicClient>> evicted;
1401 for (auto& i : mActiveClientManager.getAll()) {
1402 auto clientSp = i->getValue();
1403 if (clientSp.get() == nullptr) {
1404 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1405 mActiveClientManager.remove(i);
1406 continue;
1407 }
1408 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1409 callingPid == clientSp->getClientPid())) {
1410 mActiveClientManager.remove(i);
1411 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001412
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 // Notify the client of disconnection
1414 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1415 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001416 }
1417 }
1418
Ruben Brunkcc776712015-02-17 20:18:47 -08001419 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1420 // other clients from connecting in mServiceLockWrapper if held
1421 mServiceLock.unlock();
1422
Ruben Brunk36597b22015-03-20 22:15:57 -07001423 // Do not clear caller identity, remote caller should be client proccess
1424
Ruben Brunkcc776712015-02-17 20:18:47 -08001425 for (auto& i : evicted) {
1426 if (i.get() != nullptr) {
1427 i->disconnect();
1428 ret = true;
1429 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001430 }
1431
Ruben Brunkcc776712015-02-17 20:18:47 -08001432 // Reacquire mServiceLock
1433 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001434
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 } // lock is destroyed, allow further connect calls
1436
1437 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001438}
1439
Igor Murashkinecf17e82012-10-02 16:05:11 -07001440
Ruben Brunkcc776712015-02-17 20:18:47 -08001441std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1442 const String8& cameraId) const {
1443 std::shared_ptr<CameraState> state;
1444 {
1445 Mutex::Autolock lock(mCameraStatesLock);
1446 auto iter = mCameraStates.find(cameraId);
1447 if (iter != mCameraStates.end()) {
1448 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449 }
1450 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001451 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452}
1453
Ruben Brunkcc776712015-02-17 20:18:47 -08001454sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1455 // Remove from active clients list
1456 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1457 if (clientDescriptorPtr == nullptr) {
1458 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1459 cameraId.string());
1460 return sp<BasicClient>{nullptr};
1461 }
1462
1463 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001464}
1465
Ruben Brunk36597b22015-03-20 22:15:57 -07001466void CameraService::doUserSwitch(int newUserId) {
1467 // Acquire mServiceLock and prevent other clients from connecting
1468 std::unique_ptr<AutoConditionLock> lock =
1469 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1470
1471 if (newUserId <= 0) {
1472 ALOGW("%s: Bad user ID %d given during user switch, resetting to default.", __FUNCTION__,
1473 newUserId);
1474 newUserId = DEFAULT_LAST_USER_ID;
1475 }
1476
Ruben Brunka8ca9152015-04-07 14:23:40 -07001477 logUserSwitch(mLastUserId, newUserId);
1478
Ruben Brunk36597b22015-03-20 22:15:57 -07001479 mLastUserId = newUserId;
1480
1481 // Current user has switched, evict all current clients.
1482 std::vector<sp<BasicClient>> evicted;
1483 for (auto& i : mActiveClientManager.getAll()) {
1484 auto clientSp = i->getValue();
1485
1486 if (clientSp.get() == nullptr) {
1487 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1488 continue;
1489 }
1490
1491 evicted.push_back(clientSp);
1492
1493 String8 curTime = getFormattedCurrentTime();
1494
1495 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1496 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001497
Ruben Brunk36597b22015-03-20 22:15:57 -07001498 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001499 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001500 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001501 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1502 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001503
1504 }
1505
1506 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1507 // blocking other clients from connecting in mServiceLockWrapper if held.
1508 mServiceLock.unlock();
1509
1510 // Clear caller identity temporarily so client disconnect PID checks work correctly
1511 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1512
1513 for (auto& i : evicted) {
1514 i->disconnect();
1515 }
1516
1517 IPCThreadState::self()->restoreCallingIdentity(token);
1518
1519 // Reacquire mServiceLock
1520 mServiceLock.lock();
1521}
Ruben Brunkcc776712015-02-17 20:18:47 -08001522
Ruben Brunka8ca9152015-04-07 14:23:40 -07001523void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001525 Mutex::Autolock l(mLogLock);
1526 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527}
1528
Ruben Brunka8ca9152015-04-07 14:23:40 -07001529void CameraService::logDisconnected(const char* cameraId, int clientPid,
1530 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001532 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1533 clientPackage, clientPid));
1534}
1535
1536void CameraService::logConnected(const char* cameraId, int clientPid,
1537 const char* clientPackage) {
1538 // Log the clients evicted
1539 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1540 clientPackage, clientPid));
1541}
1542
1543void CameraService::logRejected(const char* cameraId, int clientPid,
1544 const char* clientPackage, const char* reason) {
1545 // Log the client rejected
1546 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1547 cameraId, clientPackage, clientPid, reason));
1548}
1549
1550void CameraService::logUserSwitch(int oldUserId, int newUserId) {
1551 // Log the new and old users
1552 logEvent(String8::format("USER_SWITCH from old user: %d , to new user: %d", oldUserId,
1553 newUserId));
1554}
1555
1556void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1557 // Log the device removal
1558 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1559}
1560
1561void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1562 // Log the device removal
1563 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1564}
1565
1566void CameraService::logClientDied(int clientPid, const char* reason) {
1567 // Log the device removal
1568 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001569}
1570
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001571void CameraService::logServiceError(const char* msg, int errorCode) {
1572 String8 curTime = getFormattedCurrentTime();
1573 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1574}
1575
Ruben Brunk36597b22015-03-20 22:15:57 -07001576status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1577 uint32_t flags) {
1578
1579 const int pid = getCallingPid();
1580 const int selfPid = getpid();
1581
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 // Permission checks
1583 switch (code) {
1584 case BnCameraService::CONNECT:
Eino-Ville Talvala63d877f2014-06-16 19:21:12 -07001585 case BnCameraService::CONNECT_DEVICE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001586 case BnCameraService::CONNECT_LEGACY: {
1587 if (pid != selfPid) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 // we're called from a different process, do the real check
1589 if (!checkCallingPermission(
1590 String16("android.permission.CAMERA"))) {
1591 const int uid = getCallingUid();
Steve Block29357bc2012-01-06 19:20:56 +00001592 ALOGE("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 "can't use the camera pid=%d, uid=%d", pid, uid);
1594 return PERMISSION_DENIED;
1595 }
1596 }
1597 break;
Ruben Brunk36597b22015-03-20 22:15:57 -07001598 }
1599 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1600 if (pid != selfPid) {
1601 // Ensure we're being called by system_server, or similar process with
1602 // permissions to notify the camera service about system events
1603 if (!checkCallingPermission(
1604 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1605 const int uid = getCallingUid();
1606 ALOGE("Permission Denial: cannot send updates to camera service about system"
1607 " events from pid=%d, uid=%d", pid, uid);
1608 return PERMISSION_DENIED;
1609 }
1610 }
1611 break;
1612 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613 }
1614
1615 return BnCameraService::onTransact(code, data, reply, flags);
1616}
1617
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618// We share the media players for shutter and recording sound for all clients.
1619// A reference count is kept to determine when we will actually release the
1620// media players.
1621
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001622MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001624 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001625 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626 mp->prepare();
1627 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001628 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 return NULL;
1630 }
1631 return mp;
1632}
1633
1634void CameraService::loadSound() {
1635 Mutex::Autolock lock(mSoundLock);
1636 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1637 if (mSoundRef++) return;
1638
1639 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1640 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1641}
1642
1643void CameraService::releaseSound() {
1644 Mutex::Autolock lock(mSoundLock);
1645 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1646 if (--mSoundRef) return;
1647
1648 for (int i = 0; i < NUM_SOUNDS; i++) {
1649 if (mSoundPlayer[i] != 0) {
1650 mSoundPlayer[i]->disconnect();
1651 mSoundPlayer[i].clear();
1652 }
1653 }
1654}
1655
1656void CameraService::playSound(sound_kind kind) {
1657 LOG1("playSound(%d)", kind);
1658 Mutex::Autolock lock(mSoundLock);
1659 sp<MediaPlayer> player = mSoundPlayer[kind];
1660 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001661 player->seekTo(0);
1662 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 }
1664}
1665
1666// ----------------------------------------------------------------------------
1667
1668CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001669 const sp<ICameraClient>& cameraClient,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001670 const String16& clientPackageName,
1671 int cameraId, int cameraFacing,
1672 int clientPid, uid_t clientUid,
1673 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001674 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001675 IInterface::asBinder(cameraClient),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001676 clientPackageName,
1677 cameraId, cameraFacing,
1678 clientPid, clientUid,
1679 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001680{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001682 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001684 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001687
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001688 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689}
1690
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691// tear down the client
1692CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001693 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001694 mDestructionStarted = true;
1695
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001696 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001697 // unconditionally disconnect. function is idempotent
1698 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699}
1700
Igor Murashkin634a5152013-02-20 17:15:11 -08001701CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001702 const sp<IBinder>& remoteCallback,
1703 const String16& clientPackageName,
1704 int cameraId, int cameraFacing,
1705 int clientPid, uid_t clientUid,
1706 int servicePid):
Ruben Brunkcc776712015-02-17 20:18:47 -08001707 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001708{
1709 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001710 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001711 mCameraId = cameraId;
1712 mCameraFacing = cameraFacing;
1713 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001714 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001715 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001716 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001717 mDestructionStarted = false;
1718}
1719
1720CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001721 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001722 mDestructionStarted = true;
1723}
1724
1725void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001726 if (mDisconnected) {
1727 ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1728 mCameraId);
1729 return;
1730 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001731 mDisconnected = true;;
1732
1733 mCameraService->removeByClient(this);
1734 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
1735 String8(mClientPackageName));
1736
1737 sp<IBinder> remote = getRemote();
1738 if (remote != nullptr) {
1739 remote->unlinkToDeath(mCameraService);
1740 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001741
1742 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001743 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1744
Igor Murashkincba2c162013-03-20 15:56:31 -07001745 // client shouldn't be able to call into us anymore
1746 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001747}
1748
Ruben Brunkcc776712015-02-17 20:18:47 -08001749String16 CameraService::BasicClient::getPackageName() const {
1750 return mClientPackageName;
1751}
1752
1753
1754int CameraService::BasicClient::getClientPid() const {
1755 return mClientPid;
1756}
1757
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001758status_t CameraService::BasicClient::startCameraOps() {
1759 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001760 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001761 mOpsCallback = new OpsCallback(this);
1762
Igor Murashkine6800ce2013-03-04 17:25:57 -08001763 {
1764 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1765 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1766 }
1767
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001768 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1769 mClientPackageName, mOpsCallback);
1770 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1771 mClientUid, mClientPackageName);
1772
1773 if (res != AppOpsManager::MODE_ALLOWED) {
1774 ALOGI("Camera %d: Access for \"%s\" has been revoked",
1775 mCameraId, String8(mClientPackageName).string());
1776 return PERMISSION_DENIED;
1777 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001778
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001779 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001780
1781 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1782 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001783 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001784
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001785 return OK;
1786}
1787
1788status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001789 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001790 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001791 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001792 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1793 mClientPackageName);
1794 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001795
Ruben Brunkcc776712015-02-17 20:18:47 -08001796 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1797 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001798
Ruben Brunkcc776712015-02-17 20:18:47 -08001799 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001800 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001801 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001802
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001803 // Notify flashlight that a camera device is closed.
1804 mCameraService->mFlashlight->deviceClosed(
1805 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001806 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001807 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001808 if (mOpsCallback != NULL) {
1809 mAppOpsManager.stopWatchingMode(mOpsCallback);
1810 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001811 mOpsCallback.clear();
1812
1813 return OK;
1814}
1815
1816void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1817 String8 name(packageName);
1818 String8 myName(mClientPackageName);
1819
1820 if (op != AppOpsManager::OP_CAMERA) {
1821 ALOGW("Unexpected app ops notification received: %d", op);
1822 return;
1823 }
1824
1825 int32_t res;
1826 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1827 mClientUid, mClientPackageName);
1828 ALOGV("checkOp returns: %d, %s ", res,
1829 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1830 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1831 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1832 "UNKNOWN");
1833
1834 if (res != AppOpsManager::MODE_ALLOWED) {
1835 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1836 myName.string());
1837 // Reset the client PID to allow server-initiated disconnect,
1838 // and to prevent further calls by client.
1839 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07001840 CaptureResultExtras resultExtras; // a dummy result (invalid)
1841 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001842 disconnect();
1843 }
1844}
1845
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846// ----------------------------------------------------------------------------
1847
Ruben Brunkcc776712015-02-17 20:18:47 -08001848// Provide client strong pointer for callbacks.
1849sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
1850 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
1851 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
1852 if (clientDescriptor != nullptr) {
1853 return sp<Client>{
1854 static_cast<Client*>(clientDescriptor->getValue().get())};
1855 }
1856 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857}
1858
Jianing Weicb0652e2014-03-12 18:29:36 -07001859void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1860 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001861 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001862}
1863
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001864// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07001865void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001866 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08001867 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08001868}
1869
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001870CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1871 mClient(client) {
1872}
1873
1874void CameraService::Client::OpsCallback::opChanged(int32_t op,
1875 const String16& packageName) {
1876 sp<BasicClient> client = mClient.promote();
1877 if (client != NULL) {
1878 client->opChanged(op, packageName);
1879 }
1880}
1881
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08001883// CameraState
1884// ----------------------------------------------------------------------------
1885
1886CameraService::CameraState::CameraState(const String8& id, int cost,
1887 const std::set<String8>& conflicting) : mId(id),
1888 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
1889
1890CameraService::CameraState::~CameraState() {}
1891
1892ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
1893 Mutex::Autolock lock(mStatusLock);
1894 return mStatus;
1895}
1896
1897CameraParameters CameraService::CameraState::getShimParams() const {
1898 return mShimParams;
1899}
1900
1901void CameraService::CameraState::setShimParams(const CameraParameters& params) {
1902 mShimParams = params;
1903}
1904
1905int CameraService::CameraState::getCost() const {
1906 return mCost;
1907}
1908
1909std::set<String8> CameraService::CameraState::getConflicting() const {
1910 return mConflicting;
1911}
1912
1913String8 CameraService::CameraState::getId() const {
1914 return mId;
1915}
1916
1917// ----------------------------------------------------------------------------
1918// CameraClientManager
1919// ----------------------------------------------------------------------------
1920
1921CameraService::CameraClientManager::~CameraClientManager() {}
1922
1923sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
1924 const String8& id) const {
1925 auto descriptor = get(id);
1926 if (descriptor == nullptr) {
1927 return sp<BasicClient>{nullptr};
1928 }
1929 return descriptor->getValue();
1930}
1931
1932String8 CameraService::CameraClientManager::toString() const {
1933 auto all = getAll();
1934 String8 ret("[");
1935 bool hasAny = false;
1936 for (auto& i : all) {
1937 hasAny = true;
1938 String8 key = i->getKey();
1939 int32_t cost = i->getCost();
1940 int32_t pid = i->getOwnerId();
1941 int32_t priority = i->getPriority();
1942 auto conflicting = i->getConflicting();
1943 auto clientSp = i->getValue();
1944 String8 packageName;
1945 if (clientSp.get() != nullptr) {
1946 packageName = String8{clientSp->getPackageName()};
1947 }
1948 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
1949 PRId32 ", ", key.string(), cost, pid, priority);
1950
1951 if (packageName.size() != 0) {
1952 ret.appendFormat("Client Package Name: %s", packageName.string());
1953 }
1954
1955 ret.append(", Conflicting Client Devices: {");
1956 for (auto& j : conflicting) {
1957 ret.appendFormat("%s, ", j.string());
1958 }
1959 ret.append("})");
1960 }
1961 if (hasAny) ret.append("\n");
1962 ret.append("]\n");
1963 return ret;
1964}
1965
1966CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1967 const String8& key, const sp<BasicClient>& value, int32_t cost,
1968 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
1969
1970 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
1971 key, value, cost, conflictingKeys, priority, ownerId);
1972}
1973
1974CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1975 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
1976 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
1977 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
1978}
1979
1980// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981
1982static const int kDumpLockRetries = 50;
1983static const int kDumpLockSleep = 60000;
1984
1985static bool tryLock(Mutex& mutex)
1986{
1987 bool locked = false;
1988 for (int i = 0; i < kDumpLockRetries; ++i) {
1989 if (mutex.tryLock() == NO_ERROR) {
1990 locked = true;
1991 break;
1992 }
1993 usleep(kDumpLockSleep);
1994 }
1995 return locked;
1996}
1997
1998status_t CameraService::dump(int fd, const Vector<String16>& args) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001999 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002001 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 "can't dump CameraService from pid=%d, uid=%d\n",
2003 getCallingPid(),
2004 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 write(fd, result.string(), result.size());
2006 } else {
2007 bool locked = tryLock(mServiceLock);
2008 // failed to lock - CameraService is probably deadlocked
2009 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002010 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002011 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 }
2013
2014 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002015 if (!mModule) {
2016 result = String8::format("No camera module available!\n");
2017 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002018
2019 // Dump event log for error information
2020 dumpEventLog(fd);
2021
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002022 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002023 return NO_ERROR;
2024 }
2025
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002026 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2027 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2028 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2029 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002030 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2031 String8 activeClientString = mActiveClientManager.toString();
2032 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2033
Ruben Brunkf81648e2014-04-17 16:14:57 -07002034 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2035 if (desc == NULL) {
2036 result.appendFormat("Vendor tags left unimplemented.\n");
2037 } else {
2038 result.appendFormat("Vendor tag definitions:\n");
2039 }
2040
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002041 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002042
2043 if (desc != NULL) {
2044 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2045 }
2046
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002047 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002048
2049 bool stateLocked = tryLock(mCameraStatesLock);
2050 if (!stateLocked) {
2051 result = String8::format("CameraStates in use, may be deadlocked\n");
2052 write(fd, result.string(), result.size());
2053 }
2054
2055 for (auto& state : mCameraStates) {
2056 String8 cameraId = state.first;
2057 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002058 camera_info info;
2059
Ruben Brunkcc776712015-02-17 20:18:47 -08002060 // TODO: Change getCameraInfo + HAL to use String cameraIds
2061 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002062 if (rc != OK) {
2063 result.appendFormat(" Error reading static information!\n");
2064 write(fd, result.string(), result.size());
2065 } else {
2066 result.appendFormat(" Facing: %s\n",
2067 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2068 result.appendFormat(" Orientation: %d\n", info.orientation);
2069 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002070 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002071 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2072 } else {
2073 deviceVersion = info.device_version;
2074 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002075
2076 auto conflicting = state.second->getConflicting();
2077 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2078 result.appendFormat(" Conflicting Devices:");
2079 for (auto& id : conflicting) {
2080 result.appendFormat(" %s", cameraId.string());
2081 }
2082 if (conflicting.size() == 0) {
2083 result.appendFormat(" NONE");
2084 }
2085 result.appendFormat("\n");
2086
2087 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002088 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2089 result.appendFormat(" Device static metadata:\n");
2090 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002091 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002092 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002093 } else {
2094 write(fd, result.string(), result.size());
2095 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002096
2097 CameraParameters p = state.second->getShimParams();
2098 if (!p.isEmpty()) {
2099 result = String8::format(" Camera1 API shim is using parameters:\n ");
2100 write(fd, result.string(), result.size());
2101 p.dump(fd, args);
2102 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002103 }
2104
Ruben Brunkcc776712015-02-17 20:18:47 -08002105 auto clientDescriptor = mActiveClientManager.get(cameraId);
2106 if (clientDescriptor == nullptr) {
2107 result = String8::format(" Device %s is closed, no client instance\n",
2108 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002109 write(fd, result.string(), result.size());
2110 continue;
2111 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002113 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2114 cameraId.string());
2115 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2116 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2117
2118 auto client = clientDescriptor->getValue();
2119 result.appendFormat("Client package: %s\n",
2120 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002121 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002122
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002123 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002125
2126 if (stateLocked) mCameraStatesLock.unlock();
2127
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002129 result = String8::format("\nNo active camera clients yet.\n");
2130 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131 }
2132
2133 if (locked) mServiceLock.unlock();
2134
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002135 // Dump camera traces if there were any
2136 write(fd, "\n", 1);
2137 camera3::CameraTraces::dump(fd, args);
2138
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139 // change logging level
2140 int n = args.size();
2141 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002142 String16 verboseOption("-v");
2143 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 String8 levelStr(args[i+1]);
2145 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002146 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002148 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 }
2150 }
2151 }
2152 return NO_ERROR;
2153}
2154
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002155void CameraService::dumpEventLog(int fd) {
2156 String8 result = String8("\nPrior client events (most recent at top):\n");
2157
2158 Mutex::Autolock l(mLogLock);
2159 for (const auto& msg : mEventLog) {
2160 result.appendFormat(" %s\n", msg.string());
2161 }
2162
2163 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2164 result.append(" ...\n");
2165 } else if (mEventLog.size() == 0) {
2166 result.append(" [no events yet]\n");
2167 }
2168 result.append("\n");
2169
2170 write(fd, result.string(), result.size());
2171}
2172
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002173void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002174 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002175 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2176 if (mTorchClientMap[i] == who) {
2177 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002178 String8 cameraId = mTorchClientMap.keyAt(i);
2179 status_t res = mFlashlight->setTorchMode(cameraId, false);
2180 if (res) {
2181 ALOGE("%s: torch client died but couldn't turn off torch: "
2182 "%s (%d)", __FUNCTION__, strerror(-res), res);
2183 return;
2184 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002185 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002186 break;
2187 }
2188 }
2189}
2190
Ruben Brunkcc776712015-02-17 20:18:47 -08002191/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002192
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002193 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002194 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2195 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002196 */
2197
Ruben Brunka8ca9152015-04-07 14:23:40 -07002198 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2199
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002200 // check torch client
2201 handleTorchClientBinderDied(who);
2202
2203 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002204 if(!evictClientIdByRemote(who)) {
2205 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002206 return;
2207 }
2208
Ruben Brunkcc776712015-02-17 20:18:47 -08002209 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2210 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002211}
2212
Ruben Brunkcc776712015-02-17 20:18:47 -08002213void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2214 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002215}
2216
Ruben Brunkcc776712015-02-17 20:18:47 -08002217void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2218 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2219 // Do not lock mServiceLock here or can get into a deadlock from
2220 // connect() -> disconnect -> updateStatus
2221
2222 auto state = getCameraState(cameraId);
2223
2224 if (state == nullptr) {
2225 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2226 cameraId.string());
2227 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002228 }
2229
Ruben Brunkcc776712015-02-17 20:18:47 -08002230 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2231 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2232 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2233 (const String8& cameraId, ICameraServiceListener::Status status) {
2234
2235 // Update torch status
2236 if (status == ICameraServiceListener::STATUS_NOT_PRESENT ||
2237 status == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
2238 // Update torch status to not available when the camera device becomes not present
2239 // or not available.
2240 onTorchStatusChanged(cameraId, ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE);
2241 } else if (status == ICameraServiceListener::STATUS_PRESENT) {
2242 // Update torch status to available when the camera device becomes present or
2243 // available
2244 onTorchStatusChanged(cameraId, ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
2245 }
2246
2247 Mutex::Autolock lock(mStatusListenerLock);
2248
2249 for (auto& listener : mListenerList) {
2250 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2251 int id = cameraIdToInt(cameraId);
2252 if (id != -1) listener->onStatusChanged(status, id);
2253 }
2254 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002255}
2256
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002257status_t CameraService::getTorchStatusLocked(
2258 const String8& cameraId,
2259 ICameraServiceListener::TorchStatus *status) const {
2260 if (!status) {
2261 return BAD_VALUE;
2262 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002263 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2264 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002265 // invalid camera ID or the camera doesn't have a flash unit
2266 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002267 }
2268
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002269 *status = mTorchStatusMap.valueAt(index);
2270 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002271}
2272
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002273status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002274 ICameraServiceListener::TorchStatus status) {
2275 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2276 if (index == NAME_NOT_FOUND) {
2277 return BAD_VALUE;
2278 }
2279 ICameraServiceListener::TorchStatus& item =
2280 mTorchStatusMap.editValueAt(index);
2281 item = status;
2282
2283 return OK;
2284}
2285
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286}; // namespace android