blob: 3209be6c43f5d45443665939c53597c6a88ea91b [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Iliyan Malchev8951a972011-04-14 16:55:59 -070018//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070019
Ruben Brunkcc776712015-02-17 20:18:47 -080020#include <algorithm>
21#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070022#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080023#include <cstring>
24#include <ctime>
25#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070026#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080027#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <pthread.h>
29
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080030#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
33#include <binder/MemoryBase.h>
34#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080035#include <binder/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070037#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080038#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <hardware/hardware.h>
40#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080041#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <media/mediaplayer.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <utils/Errors.h>
44#include <utils/Log.h>
45#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080046#include <utils/Trace.h>
47#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070048#include <system/camera_metadata.h>
49#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
51#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070052#include "api1/CameraClient.h"
53#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070054#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070056#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
58namespace android {
59
60// ----------------------------------------------------------------------------
61// Logging support -- this is for debugging only
62// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070063volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Steve Blockb8a80522011-12-20 16:23:08 +000065#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
66#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070067
68static void setLogLevel(int level) {
69 android_atomic_write(level, &gLogLevel);
70}
71
72// ----------------------------------------------------------------------------
73
Igor Murashkincba2c162013-03-20 15:56:31 -070074extern "C" {
75static void camera_device_status_change(
76 const struct camera_module_callbacks* callbacks,
77 int camera_id,
78 int new_status) {
79 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080080 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070081
Ruben Brunkcc776712015-02-17 20:18:47 -080082 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
83 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070084}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080085
86static void torch_mode_status_change(
87 const struct camera_module_callbacks* callbacks,
88 const char* camera_id,
89 int new_status) {
90 if (!callbacks || !camera_id) {
91 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
92 callbacks, camera_id);
93 }
94 sp<CameraService> cs = const_cast<CameraService*>(
95 static_cast<const CameraService*>(callbacks));
96
97 ICameraServiceListener::TorchStatus status;
98 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -080099 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800100 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
101 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800102 case TORCH_MODE_STATUS_AVAILABLE_OFF:
103 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
104 break;
105 case TORCH_MODE_STATUS_AVAILABLE_ON:
106 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800107 break;
108 default:
109 ALOGE("Unknown torch status %d", new_status);
110 return;
111 }
112
113 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800114 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800115 status);
116}
Igor Murashkincba2c162013-03-20 15:56:31 -0700117} // extern "C"
118
Mathias Agopian65ab4712010-07-14 17:59:35 -0700119// ----------------------------------------------------------------------------
120
121// This is ugly and only safe if we never re-create the CameraService, but
122// should be ok for now.
123static CameraService *gCameraService;
124
Ruben Brunka8ca9152015-04-07 14:23:40 -0700125CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Ruben Brunk36597b22015-03-20 22:15:57 -0700126 mLastUserId(DEFAULT_LAST_USER_ID), mSoundRef(0), mModule(0), mFlashlight(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000127 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800129
Igor Murashkincba2c162013-03-20 15:56:31 -0700130 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800131 this->torch_mode_status_change = android::torch_mode_status_change;
132
Ruben Brunkcc776712015-02-17 20:18:47 -0800133 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134}
135
Iliyan Malchev8951a972011-04-14 16:55:59 -0700136void CameraService::onFirstRef()
137{
Ruben Brunkcc776712015-02-17 20:18:47 -0800138 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800139
Iliyan Malchev8951a972011-04-14 16:55:59 -0700140 BnCameraService::onFirstRef();
141
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800142 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700143 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
144 (const hw_module_t **)&rawModule);
145 if (err < 0) {
146 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
147 logServiceError("Could not load camera HAL module", err);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700148 mNumberOfCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700149 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700150 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800151
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700152 mModule = new CameraModule(rawModule);
153 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
154 err = mModule->init();
155 if (err != OK) {
156 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
157 strerror(-err));
158 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800159
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 mNumberOfCameras = 0;
161 delete mModule;
162 mModule = nullptr;
163 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700164 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700165
166 mNumberOfCameras = mModule->getNumberOfCameras();
167
168 mFlashlight = new CameraFlashlight(*mModule, *this);
169 status_t res = mFlashlight->findFlashUnits();
170 if (res) {
171 // impossible because we haven't open any camera devices.
172 ALOGE("Failed to find flash units.");
173 }
174
175 for (int i = 0; i < mNumberOfCameras; i++) {
176 String8 cameraId = String8::format("%d", i);
177
178 // Defaults to use for cost and conflicting devices
179 int cost = 100;
180 char** conflicting_devices = nullptr;
181 size_t conflicting_devices_length = 0;
182
183 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
184 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4) {
185 struct camera_info info;
186 status_t rc = mModule->getCameraInfo(i, &info);
187 if (rc == NO_ERROR) {
188 cost = info.resource_cost;
189 conflicting_devices = info.conflicting_devices;
190 conflicting_devices_length = info.conflicting_devices_length;
191 } else {
192 ALOGE("%s: Received error loading camera info for device %d, cost and"
193 " conflicting devices fields set to defaults for this device.",
194 __FUNCTION__, i);
195 }
196 }
197
198 std::set<String8> conflicting;
199 for (size_t i = 0; i < conflicting_devices_length; i++) {
200 conflicting.emplace(String8(conflicting_devices[i]));
201 }
202
203 // Initialize state for each camera device
204 {
205 Mutex::Autolock lock(mCameraStatesLock);
206 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
207 conflicting));
208 }
209
210 if (mFlashlight->hasFlashUnit(cameraId)) {
211 mTorchStatusMap.add(cameraId,
212 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
213 }
214 }
215
216 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
217 mModule->setCallbacks(this);
218 }
219
220 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
221
222 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
223 setUpVendorTags();
224 }
225
226 CameraDeviceFactory::registerService(this);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700227}
228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800230 if (mModule) {
231 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800232 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800233 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800234 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800235 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700236}
237
Ruben Brunkcc776712015-02-17 20:18:47 -0800238void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
239 camera_device_status_t newStatus) {
240 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700241 cameraId, newStatus);
242
Ruben Brunkcc776712015-02-17 20:18:47 -0800243 String8 id = String8::format("%d", cameraId);
244 std::shared_ptr<CameraState> state = getCameraState(id);
245
246 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700247 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
248 return;
249 }
250
Ruben Brunkcc776712015-02-17 20:18:47 -0800251 ICameraServiceListener::Status oldStatus = state->getStatus();
252
253 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
254 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700255 return;
256 }
257
Igor Murashkincba2c162013-03-20 15:56:31 -0700258 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700259 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
260 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800261 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700262 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800263 // Don't do this in updateStatus to avoid deadlock over mServiceLock
264 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700265
Ruben Brunkcc776712015-02-17 20:18:47 -0800266 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
267 // to this device until the status changes
268 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700269
Ruben Brunkcc776712015-02-17 20:18:47 -0800270 // Remove cached shim parameters
271 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700272
Ruben Brunkcc776712015-02-17 20:18:47 -0800273 // Remove the client from the list of active clients
274 clientToDisconnect = removeClientLocked(id);
275
276 // Notify the client of disconnection
277 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
278 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700279 }
280
Ruben Brunkcc776712015-02-17 20:18:47 -0800281 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
282 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700283
Ruben Brunkcc776712015-02-17 20:18:47 -0800284 // Disconnect client
285 if (clientToDisconnect.get() != nullptr) {
286 // Ensure not in binder RPC so client disconnect PID checks work correctly
287 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
288 "onDeviceStatusChanged must be called from the camera service process!");
289 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700290 }
291
Ruben Brunkcc776712015-02-17 20:18:47 -0800292 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700293 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
294 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
295 newStatus));
296 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800297 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700298 }
299
Igor Murashkincba2c162013-03-20 15:56:31 -0700300}
301
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800302void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800303 ICameraServiceListener::TorchStatus newStatus) {
304 Mutex::Autolock al(mTorchStatusMutex);
305 onTorchStatusChangedLocked(cameraId, newStatus);
306}
307
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800308void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800309 ICameraServiceListener::TorchStatus newStatus) {
310 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
311 __FUNCTION__, cameraId.string(), newStatus);
312
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800313 ICameraServiceListener::TorchStatus status;
314 status_t res = getTorchStatusLocked(cameraId, &status);
315 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700316 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
317 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800318 return;
319 }
320 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800321 return;
322 }
323
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800324 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800325 if (res) {
326 ALOGE("%s: Failed to set the torch status", __FUNCTION__,
327 (uint32_t)newStatus);
328 return;
329 }
330
Ruben Brunkcc776712015-02-17 20:18:47 -0800331 {
332 Mutex::Autolock lock(mStatusListenerLock);
333 for (auto& i : mListenerList) {
334 i->onTorchStatusChanged(newStatus, String16{cameraId});
335 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800336 }
337}
338
339
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340int32_t CameraService::getNumberOfCameras() {
341 return mNumberOfCameras;
342}
343
344status_t CameraService::getCameraInfo(int cameraId,
345 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700346 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700347 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700348 }
349
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
351 return BAD_VALUE;
352 }
353
Iliyan Malchev8951a972011-04-14 16:55:59 -0700354 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700355 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800356 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700357 cameraInfo->facing = info.facing;
358 cameraInfo->orientation = info.orientation;
359 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360}
361
Ruben Brunkcc776712015-02-17 20:18:47 -0800362int CameraService::cameraIdToInt(const String8& cameraId) {
363 errno = 0;
364 size_t pos = 0;
365 int ret = stoi(std::string{cameraId.string()}, &pos);
366 if (errno != 0 || pos != cameraId.size()) {
367 return -1;
368 }
369 return ret;
370}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700371
372status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
373 status_t ret = OK;
374 struct CameraInfo info;
375 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
376 return ret;
377 }
378
379 CameraMetadata shimInfo;
380 int32_t orientation = static_cast<int32_t>(info.orientation);
381 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
382 return ret;
383 }
384
385 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
386 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
387 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
388 return ret;
389 }
390
Igor Murashkin65d14b92014-06-17 12:03:20 -0700391 CameraParameters shimParams;
392 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
393 // Error logged by callee
394 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700395 }
396
397 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700398 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700399 Vector<int32_t> formats;
400 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700401 {
402 shimParams.getSupportedPreviewSizes(/*out*/sizes);
403 shimParams.getSupportedPreviewFormats(/*out*/formats);
404 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700405 }
406
407 // Always include IMPLEMENTATION_DEFINED
408 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
409
410 const size_t INTS_PER_CONFIG = 4;
411
412 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700413 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
414
415 Vector<int32_t> streamConfigs;
416 streamConfigs.setCapacity(streamConfigSize);
417
Ruben Brunkb2119af2014-05-09 19:57:56 -0700418 for (size_t i = 0; i < formats.size(); ++i) {
419 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700420 streamConfigs.add(formats[i]);
421 streamConfigs.add(sizes[j].width);
422 streamConfigs.add(sizes[j].height);
423 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700424 }
425 }
426
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700427 for (size_t i = 0; i < jpegSizes.size(); ++i) {
428 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
429 streamConfigs.add(jpegSizes[i].width);
430 streamConfigs.add(jpegSizes[i].height);
431 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
432 }
433
Ruben Brunkb2119af2014-05-09 19:57:56 -0700434 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700435 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700436 return ret;
437 }
438
439 int64_t fakeMinFrames[0];
440 // TODO: Fixme, don't fake min frame durations.
441 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
442 fakeMinFrames, 0)) != OK) {
443 return ret;
444 }
445
446 int64_t fakeStalls[0];
447 // TODO: Fixme, don't fake stall durations.
448 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
449 fakeStalls, 0)) != OK) {
450 return ret;
451 }
452
453 *cameraInfo = shimInfo;
454 return OK;
455}
456
Zhijun He2b59be82013-09-25 10:14:30 -0700457status_t CameraService::getCameraCharacteristics(int cameraId,
458 CameraMetadata* cameraInfo) {
459 if (!cameraInfo) {
460 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
461 return BAD_VALUE;
462 }
463
464 if (!mModule) {
465 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
466 return -ENODEV;
467 }
468
Zhijun He2b59be82013-09-25 10:14:30 -0700469 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
470 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
471 return BAD_VALUE;
472 }
473
474 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700475 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800476 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700477 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
478 /**
479 * Backwards compatibility mode for old HALs:
480 * - Convert CameraInfo into static CameraMetadata properties.
481 * - Retrieve cached CameraParameters for this camera. If none exist,
482 * attempt to open CameraClient and retrieve the CameraParameters.
483 * - Convert cached CameraParameters into static CameraMetadata
484 * properties.
485 */
486 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700487
Ruben Brunkb2119af2014-05-09 19:57:56 -0700488 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
489 return ret;
490 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700491
Ruben Brunkb2119af2014-05-09 19:57:56 -0700492 } else {
493 /**
494 * Normal HAL 2.1+ codepath.
495 */
496 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800497 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700498 *cameraInfo = info.static_camera_characteristics;
499 }
Zhijun He2b59be82013-09-25 10:14:30 -0700500
501 return ret;
502}
503
Ruben Brunkcc776712015-02-17 20:18:47 -0800504int CameraService::getCallingPid() {
505 return IPCThreadState::self()->getCallingPid();
506}
507
508int CameraService::getCallingUid() {
509 return IPCThreadState::self()->getCallingUid();
510}
511
512String8 CameraService::getFormattedCurrentTime() {
513 time_t now = time(nullptr);
514 char formattedTime[64];
515 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
516 return String8(formattedTime);
517}
518
519int CameraService::getCameraPriorityFromProcState(int procState) {
520 // Find the priority for the camera usage based on the process state. Higher priority clients
521 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700522 if (procState < 0) {
523 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
524 procState);
525 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800526 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700527 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800528}
529
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800530status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
531 if (!mModule) {
532 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
533 return -ENODEV;
534 }
535
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800536 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
537 return OK;
538}
539
Igor Murashkin634a5152013-02-20 17:15:11 -0800540int CameraService::getDeviceVersion(int cameraId, int* facing) {
541 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800542 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800543 return -1;
544 }
545
546 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800547 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800548 deviceVersion = info.device_version;
549 } else {
550 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
551 }
552
553 if (facing) {
554 *facing = info.facing;
555 }
556
557 return deviceVersion;
558}
559
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700560status_t CameraService::filterGetInfoErrorCode(status_t err) {
561 switch(err) {
562 case NO_ERROR:
563 case -EINVAL:
564 return err;
565 default:
566 break;
567 }
568 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800569}
570
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800571bool CameraService::setUpVendorTags() {
572 vendor_tag_ops_t vOps = vendor_tag_ops_t();
573
574 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800575 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800576 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
577 return false;
578 }
579
580 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800581 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800582 ATRACE_END();
583
584 // Ensure all vendor operations are present
585 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
586 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
587 vOps.get_tag_type == NULL) {
588 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
589 , __FUNCTION__);
590 return false;
591 }
592
593 // Read all vendor tag definitions into a descriptor
594 sp<VendorTagDescriptor> desc;
595 status_t res;
596 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
597 != OK) {
598 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
599 "received error %s (%d). Camera clients will not be able to use"
600 "vendor tags", __FUNCTION__, strerror(res), res);
601 return false;
602 }
603
604 // Set the global descriptor to use with camera metadata
605 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
606 return true;
607}
608
Ruben Brunkcc776712015-02-17 20:18:47 -0800609status_t CameraService::makeClient(const sp<CameraService>& cameraService,
610 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
611 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
612 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
613 /*out*/sp<BasicClient>* client) {
614
615 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
616 int id = cameraIdToInt(cameraId);
617 if (id == -1) {
618 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
619 cameraId.string());
620 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700621 }
622
Ruben Brunkcc776712015-02-17 20:18:47 -0800623 if (halVersion < 0 || halVersion == deviceVersion) {
624 // Default path: HAL version is unspecified by caller, create CameraClient
625 // based on device version reported by the HAL.
626 switch(deviceVersion) {
627 case CAMERA_DEVICE_API_VERSION_1_0:
628 if (effectiveApiLevel == API_1) { // Camera1 API route
629 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
630 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
631 clientPid, clientUid, getpid(), legacyMode);
632 } else { // Camera2 API route
633 ALOGW("Camera using old HAL version: %d", deviceVersion);
634 return -EOPNOTSUPP;
635 }
636 break;
637 case CAMERA_DEVICE_API_VERSION_2_0:
638 case CAMERA_DEVICE_API_VERSION_2_1:
639 case CAMERA_DEVICE_API_VERSION_3_0:
640 case CAMERA_DEVICE_API_VERSION_3_1:
641 case CAMERA_DEVICE_API_VERSION_3_2:
642 case CAMERA_DEVICE_API_VERSION_3_3:
643 if (effectiveApiLevel == API_1) { // Camera1 API route
644 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
645 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
646 clientPid, clientUid, servicePid, legacyMode);
647 } else { // Camera2 API route
648 sp<ICameraDeviceCallbacks> tmp =
649 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
650 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
651 facing, clientPid, clientUid, servicePid);
652 }
653 break;
654 default:
655 // Should not be reachable
656 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
657 return INVALID_OPERATION;
658 }
659 } else {
660 // A particular HAL version is requested by caller. Create CameraClient
661 // based on the requested HAL version.
662 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
663 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
664 // Only support higher HAL version device opened as HAL1.0 device.
665 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
666 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
667 clientPid, clientUid, servicePid, legacyMode);
668 } else {
669 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
670 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
671 " opened as HAL %x device", halVersion, deviceVersion,
672 CAMERA_DEVICE_API_VERSION_1_0);
673 return INVALID_OPERATION;
674 }
675 }
676 return NO_ERROR;
677}
678
679status_t CameraService::initializeShimMetadata(int cameraId) {
680 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700681
682 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800683 String8 id = String8::format("%d", cameraId);
684 status_t ret = NO_ERROR;
685 sp<Client> tmp = nullptr;
686 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
687 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
688 false, true, tmp)) != NO_ERROR) {
689 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
690 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700691 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800692 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700693}
694
Igor Murashkin65d14b92014-06-17 12:03:20 -0700695status_t CameraService::getLegacyParametersLazy(int cameraId,
696 /*out*/
697 CameraParameters* parameters) {
698
699 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
700
701 status_t ret = 0;
702
703 if (parameters == NULL) {
704 ALOGE("%s: parameters must not be null", __FUNCTION__);
705 return BAD_VALUE;
706 }
707
Ruben Brunkcc776712015-02-17 20:18:47 -0800708 String8 id = String8::format("%d", cameraId);
709
710 // Check if we already have parameters
711 {
712 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700713 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800714 auto cameraState = getCameraState(id);
715 if (cameraState == nullptr) {
716 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
717 return BAD_VALUE;
718 }
719 CameraParameters p = cameraState->getShimParams();
720 if (!p.isEmpty()) {
721 *parameters = p;
722 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700723 }
724 }
725
Ruben Brunkcc776712015-02-17 20:18:47 -0800726 int64_t token = IPCThreadState::self()->clearCallingIdentity();
727 ret = initializeShimMetadata(cameraId);
728 IPCThreadState::self()->restoreCallingIdentity(token);
729 if (ret != NO_ERROR) {
730 // Error already logged by callee
731 return ret;
732 }
733
734 // Check for parameters again
735 {
736 // Scope for service lock
737 Mutex::Autolock lock(mServiceLock);
738 auto cameraState = getCameraState(id);
739 if (cameraState == nullptr) {
740 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
741 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700742 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800743 CameraParameters p = cameraState->getShimParams();
744 if (!p.isEmpty()) {
745 *parameters = p;
746 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700747 }
748 }
749
Ruben Brunkcc776712015-02-17 20:18:47 -0800750 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
751 __FUNCTION__);
752 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700753}
754
Ruben Brunk36597b22015-03-20 22:15:57 -0700755status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
756 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800757
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500759
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800760 if (clientUid == USE_CALLING_UID) {
761 clientUid = getCallingUid();
762 } else {
763 // We only trust our own process to forward client UIDs
764 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700765 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
766 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700767 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800768 }
769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770
Iliyan Malchev8951a972011-04-14 16:55:59 -0700771 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800772 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
773 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700774 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700775 }
776
Ruben Brunkcc776712015-02-17 20:18:47 -0800777 if (getCameraState(cameraId) == nullptr) {
778 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
779 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700780 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 }
782
Ruben Brunkcc776712015-02-17 20:18:47 -0800783 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800784 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800785 char key[PROPERTY_KEY_MAX];
786 int clientUserId = multiuser_get_user_id(clientUid);
787 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
788 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800789 if (strcmp(value, "1") == 0) {
790 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800791 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
792 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700793 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800794 }
795
Ruben Brunka8ca9152015-04-07 14:23:40 -0700796 // Only allow clients who are being used by the current foreground device user, unless calling
797 // from our own process.
798 if (callingPid != getpid() &&
799 (mLastUserId != clientUserId && mLastUserId != DEFAULT_LAST_USER_ID)) {
800 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from previous "
801 "device user %d, current device user %d)", callingPid, clientUserId, mLastUserId);
Ruben Brunk36597b22015-03-20 22:15:57 -0700802 return PERMISSION_DENIED;
803 }
804
Ruben Brunkcc776712015-02-17 20:18:47 -0800805 return checkIfDeviceIsUsable(cameraId);
806}
807
808status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
809 auto cameraState = getCameraState(cameraId);
810 int callingPid = getCallingPid();
811 if (cameraState == nullptr) {
812 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
813 cameraId.string());
814 return -ENODEV;
815 }
816
817 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700818 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800819 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
820 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700821 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700822 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800823 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
824 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700825 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700826 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700827
Ruben Brunkcc776712015-02-17 20:18:47 -0800828 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800829}
830
Ruben Brunkcc776712015-02-17 20:18:47 -0800831void CameraService::finishConnectLocked(const sp<BasicClient>& client,
832 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800833
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 // Make a descriptor for the incoming client
835 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
836 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
837
838 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
839 String8(client->getPackageName()));
840
841 if (evicted.size() > 0) {
842 // This should never happen - clients should already have been removed in disconnect
843 for (auto& i : evicted) {
844 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
845 __FUNCTION__, i->getKey().string());
846 }
847
848 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
849 __FUNCTION__);
850 }
851}
852
853status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
854 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
855 /*out*/
856 sp<BasicClient>* client,
857 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
858
859 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700860 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800861 DescriptorPtr clientDescriptor;
862 {
863 if (effectiveApiLevel == API_1) {
864 // If we are using API1, any existing client for this camera ID with the same remote
865 // should be returned rather than evicted to allow MediaRecorder to work properly.
866
867 auto current = mActiveClientManager.get(cameraId);
868 if (current != nullptr) {
869 auto clientSp = current->getValue();
870 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700871 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
872 ALOGW("CameraService connect called from same client, but with a different"
873 " API level, evicting prior client...");
874 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800875 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700876 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800877 *client = clientSp;
878 return NO_ERROR;
879 }
880 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800881 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800882 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800883
Ruben Brunkcc776712015-02-17 20:18:47 -0800884 // Return error if the device was unplugged or removed by the HAL for some reason
885 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
886 return ret;
887 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800888
Ruben Brunkcc776712015-02-17 20:18:47 -0800889 // Get current active client PIDs
890 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
891 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800892
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700893 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
894 // address of PROCESS_STATE_NONEXISTENT as a reference argument
895 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
896 // not have an out-of-class definition.
897 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800898
Ruben Brunkcc776712015-02-17 20:18:47 -0800899 // Get priorites of all active PIDs
900 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
901 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700902
Ruben Brunkcc776712015-02-17 20:18:47 -0800903 // Update all active clients' priorities
904 std::map<int,int> pidToPriorityMap;
905 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
906 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
907 }
908 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800909
Ruben Brunkcc776712015-02-17 20:18:47 -0800910 // Get state for the given cameraId
911 auto state = getCameraState(cameraId);
912 if (state == nullptr) {
913 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
914 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700915 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -0700916 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800917
918 // Make descriptor for incoming client
919 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
920 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
921 state->getConflicting(),
922 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
923
924 // Find clients that would be evicted
925 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
926
927 // If the incoming client was 'evicted,' higher priority clients have the camera in the
928 // background, so we cannot do evictions
929 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
930 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
931 " priority).", clientPid);
932
933 sp<BasicClient> clientSp = clientDescriptor->getValue();
934 String8 curTime = getFormattedCurrentTime();
935 auto incompatibleClients =
936 mActiveClientManager.getIncompatibleClients(clientDescriptor);
937
938 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -0700939 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800940 cameraId.string(), packageName.string(), clientPid,
941 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
942
943 for (auto& i : incompatibleClients) {
944 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
945 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
946 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
947 i->getPriority());
948 }
949
950 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -0700951 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800952 mEventLog.add(msg);
953
954 return -EBUSY;
955 }
956
957 for (auto& i : evicted) {
958 sp<BasicClient> clientSp = i->getValue();
959 if (clientSp.get() == nullptr) {
960 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
961
962 // TODO: Remove this
963 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
964 __FUNCTION__);
965 mActiveClientManager.remove(i);
966 continue;
967 }
968
969 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
970 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700971 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -0800972
Ruben Brunkcc776712015-02-17 20:18:47 -0800973 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -0700974 logEvent(String8::format("EVICT device %s client held by package %s (PID"
975 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
976 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -0800977 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
978 i->getOwnerId(), i->getPriority(), cameraId.string(),
979 packageName.string(), clientPid,
980 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
981
982 // Notify the client of disconnection
983 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
984 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700985 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700986 }
987
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
989 // other clients from connecting in mServiceLockWrapper if held
990 mServiceLock.unlock();
991
992 // Clear caller identity temporarily so client disconnect PID checks work correctly
993 int64_t token = IPCThreadState::self()->clearCallingIdentity();
994
995 // Destroy evicted clients
996 for (auto& i : evictedClients) {
997 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700998 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -0800999 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001000
1001 IPCThreadState::self()->restoreCallingIdentity(token);
1002
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001003 for (const auto& i : evictedClients) {
1004 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1005 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1006 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1007 if (ret == TIMED_OUT) {
1008 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1009 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1010 mActiveClientManager.toString().string());
1011 return -EBUSY;
1012 }
1013 if (ret != NO_ERROR) {
1014 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1015 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1016 ret, mActiveClientManager.toString().string());
1017 return ret;
1018 }
1019 }
1020
1021 evictedClients.clear();
1022
Ruben Brunkcc776712015-02-17 20:18:47 -08001023 // Once clients have been disconnected, relock
1024 mServiceLock.lock();
1025
1026 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1027 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1028 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001029 }
1030
Ruben Brunkcc776712015-02-17 20:18:47 -08001031 *partial = clientDescriptor;
1032 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001033}
1034
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001035status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001036 const sp<ICameraClient>& cameraClient,
1037 int cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001038 const String16& opPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001039 int clientUid,
1040 /*out*/
1041 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001042
Svet Ganov32fa6d02015-05-01 20:47:20 -07001043 const status_t result = checkCameraAccess(opPackageName);
1044 if (result != NO_ERROR) {
1045 return result;
1046 }
1047
Ruben Brunkcc776712015-02-17 20:18:47 -08001048 status_t ret = NO_ERROR;
1049 String8 id = String8::format("%d", cameraId);
1050 sp<Client> client = nullptr;
1051 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001052 opPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001053
Ruben Brunkcc776712015-02-17 20:18:47 -08001054 if(ret != NO_ERROR) {
Svet Ganov32fa6d02015-05-01 20:47:20 -07001055 logRejected(id, getCallingPid(), String8(opPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001056 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001057 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 }
1059
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001060 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001061 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062}
1063
Zhijun Heb10cdad2014-06-16 16:38:35 -07001064status_t CameraService::connectLegacy(
1065 const sp<ICameraClient>& cameraClient,
1066 int cameraId, int halVersion,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001067 const String16& opPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001068 int clientUid,
1069 /*out*/
1070 sp<ICamera>& device) {
1071
Svet Ganov32fa6d02015-05-01 20:47:20 -07001072 const status_t result = checkCameraAccess(opPackageName);
1073 if (result != NO_ERROR) {
1074 return result;
1075 }
1076
Ruben Brunka8ca9152015-04-07 14:23:40 -07001077 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001078 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001079 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001080 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001081 /*
1082 * Either the HAL version is unspecified in which case this just creates
1083 * a camera client selected by the latest device version, or
1084 * it's a particular version in which case the HAL must supported
1085 * the open_legacy call
1086 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001087 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001088 __FUNCTION__, apiVersion);
Svet Ganov32fa6d02015-05-01 20:47:20 -07001089 logRejected(id, getCallingPid(), String8(opPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001090 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001091 return INVALID_OPERATION;
1092 }
1093
Ruben Brunkcc776712015-02-17 20:18:47 -08001094 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001095 sp<Client> client = nullptr;
Svet Ganov32fa6d02015-05-01 20:47:20 -07001096 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, opPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001097 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001098
Ruben Brunkcc776712015-02-17 20:18:47 -08001099 if(ret != NO_ERROR) {
Svet Ganov32fa6d02015-05-01 20:47:20 -07001100 logRejected(id, getCallingPid(), String8(opPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001101 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001102 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001103 }
1104
Zhijun Heb10cdad2014-06-16 16:38:35 -07001105 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001106 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001107}
1108
Ruben Brunkcc776712015-02-17 20:18:47 -08001109status_t CameraService::connectDevice(
1110 const sp<ICameraDeviceCallbacks>& cameraCb,
1111 int cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001112 const String16& opPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001113 int clientUid,
1114 /*out*/
1115 sp<ICameraDeviceUser>& device) {
1116
Svet Ganov32fa6d02015-05-01 20:47:20 -07001117 const status_t result = checkCameraAccess(opPackageName);
1118 if (result != NO_ERROR) {
1119 return result;
1120 }
1121
Ruben Brunkcc776712015-02-17 20:18:47 -08001122 status_t ret = NO_ERROR;
1123 String8 id = String8::format("%d", cameraId);
1124 sp<CameraDeviceClient> client = nullptr;
1125 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001126 CAMERA_HAL_API_VERSION_UNSPECIFIED, opPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001127 /*out*/client);
1128
1129 if(ret != NO_ERROR) {
Svet Ganov32fa6d02015-05-01 20:47:20 -07001130 logRejected(id, getCallingPid(), String8(opPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001131 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001133 }
1134
Ruben Brunkcc776712015-02-17 20:18:47 -08001135 device = client;
1136 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001137}
1138
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001139status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1140 const sp<IBinder>& clientBinder) {
1141 if (enabled && clientBinder == NULL) {
1142 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001143 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001144 }
1145
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001146 String8 id = String8(cameraId.string());
1147
1148 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001149 auto state = getCameraState(id);
1150 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001151 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001152 return -EINVAL;
1153 }
1154
1155 ICameraServiceListener::Status cameraStatus = state->getStatus();
1156 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1157 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001158 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001159 return -EINVAL;
1160 }
1161
1162 {
1163 Mutex::Autolock al(mTorchStatusMutex);
1164 ICameraServiceListener::TorchStatus status;
1165 status_t res = getTorchStatusLocked(id, &status);
1166 if (res) {
1167 ALOGE("%s: getting current torch status failed for camera %s",
1168 __FUNCTION__, id.string());
1169 return -EINVAL;
1170 }
1171
1172 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001173 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001174 ALOGE("%s: torch mode of camera %s is not available because "
1175 "camera is in use", __FUNCTION__, id.string());
1176 return -EBUSY;
1177 } else {
1178 ALOGE("%s: torch mode of camera %s is not available due to "
1179 "insufficient resources", __FUNCTION__, id.string());
1180 return -EUSERS;
1181 }
1182 }
1183 }
1184
1185 status_t res = mFlashlight->setTorchMode(id, enabled);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001186 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001187 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1188 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001189 return res;
1190 }
1191
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001192 {
1193 // update the link to client's death
1194 Mutex::Autolock al(mTorchClientMapMutex);
1195 ssize_t index = mTorchClientMap.indexOfKey(id);
1196 if (enabled) {
1197 if (index == NAME_NOT_FOUND) {
1198 mTorchClientMap.add(id, clientBinder);
1199 } else {
1200 const sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
1201 oldBinder->unlinkToDeath(this);
1202
1203 mTorchClientMap.replaceValueAt(index, clientBinder);
1204 }
1205 clientBinder->linkToDeath(this);
1206 } else if (index != NAME_NOT_FOUND) {
1207 sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001208 oldBinder->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001209 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001210 }
1211
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001212 return OK;
1213}
1214
Ruben Brunk36597b22015-03-20 22:15:57 -07001215void CameraService::notifySystemEvent(int eventId, int arg0) {
1216 switch(eventId) {
1217 case ICameraService::USER_SWITCHED: {
1218 doUserSwitch(/*newUserId*/arg0);
1219 break;
1220 }
1221 case ICameraService::NO_EVENT:
1222 default: {
1223 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1224 eventId);
1225 break;
1226 }
1227 }
1228}
1229
Igor Murashkinbfc99152013-02-27 12:55:20 -08001230status_t CameraService::addListener(
1231 const sp<ICameraServiceListener>& listener) {
1232 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001233
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001234 if (listener == 0) {
1235 ALOGE("%s: Listener must not be null", __FUNCTION__);
1236 return BAD_VALUE;
1237 }
1238
Igor Murashkinbfc99152013-02-27 12:55:20 -08001239 Mutex::Autolock lock(mServiceLock);
1240
Ruben Brunkcc776712015-02-17 20:18:47 -08001241 {
1242 Mutex::Autolock lock(mStatusListenerLock);
1243 for (auto& it : mListenerList) {
1244 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1245 ALOGW("%s: Tried to add listener %p which was already subscribed",
1246 __FUNCTION__, listener.get());
1247 return ALREADY_EXISTS;
1248 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001249 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001250
1251 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001252 }
1253
Igor Murashkinbfc99152013-02-27 12:55:20 -08001254
Igor Murashkincba2c162013-03-20 15:56:31 -07001255 /* Immediately signal current status to this listener only */
1256 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001257 Mutex::Autolock lock(mCameraStatesLock);
1258 for (auto& i : mCameraStates) {
1259 // TODO: Update binder to use String16 for camera IDs and remove;
1260 int id = cameraIdToInt(i.first);
1261 if (id == -1) continue;
1262
1263 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001264 }
1265 }
1266
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001267 /* Immediately signal current torch status to this listener only */
1268 {
1269 Mutex::Autolock al(mTorchStatusMutex);
1270 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001271 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1272 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001273 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001274 }
1275
Igor Murashkinbfc99152013-02-27 12:55:20 -08001276 return OK;
1277}
Ruben Brunkcc776712015-02-17 20:18:47 -08001278
1279status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001280 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1281
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001282 if (listener == 0) {
1283 ALOGE("%s: Listener must not be null", __FUNCTION__);
1284 return BAD_VALUE;
1285 }
1286
Igor Murashkinbfc99152013-02-27 12:55:20 -08001287 Mutex::Autolock lock(mServiceLock);
1288
Ruben Brunkcc776712015-02-17 20:18:47 -08001289 {
1290 Mutex::Autolock lock(mStatusListenerLock);
1291 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1292 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1293 mListenerList.erase(it);
1294 return OK;
1295 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001296 }
1297 }
1298
1299 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1300 __FUNCTION__, listener.get());
1301
1302 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001303}
1304
Ruben Brunkcc776712015-02-17 20:18:47 -08001305status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001306 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1307
1308 if (parameters == NULL) {
1309 ALOGE("%s: parameters must not be null", __FUNCTION__);
1310 return BAD_VALUE;
1311 }
1312
1313 status_t ret = 0;
1314
1315 CameraParameters shimParams;
1316 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1317 // Error logged by caller
1318 return ret;
1319 }
1320
1321 String8 shimParamsString8 = shimParams.flatten();
1322 String16 shimParamsString16 = String16(shimParamsString8);
1323
1324 *parameters = shimParamsString16;
1325
1326 return OK;
1327}
1328
1329status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1330 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1331
1332 switch (apiVersion) {
1333 case API_VERSION_1:
1334 case API_VERSION_2:
1335 break;
1336 default:
1337 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1338 return BAD_VALUE;
1339 }
1340
1341 int facing = -1;
1342 int deviceVersion = getDeviceVersion(cameraId, &facing);
1343
1344 switch(deviceVersion) {
1345 case CAMERA_DEVICE_API_VERSION_1_0:
1346 case CAMERA_DEVICE_API_VERSION_2_0:
1347 case CAMERA_DEVICE_API_VERSION_2_1:
1348 case CAMERA_DEVICE_API_VERSION_3_0:
1349 case CAMERA_DEVICE_API_VERSION_3_1:
1350 if (apiVersion == API_VERSION_2) {
1351 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1352 __FUNCTION__, cameraId);
1353 return -EOPNOTSUPP;
1354 } else { // if (apiVersion == API_VERSION_1) {
1355 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1356 __FUNCTION__, cameraId);
1357 return OK;
1358 }
1359 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001361 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1362 __FUNCTION__, cameraId);
1363 return OK;
1364 case -1:
1365 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1366 return BAD_VALUE;
1367 default:
1368 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1369 return INVALID_OPERATION;
1370 }
1371
1372 return OK;
1373}
1374
Ruben Brunkcc776712015-02-17 20:18:47 -08001375void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001376 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001377 for (auto& i : mActiveClientManager.getAll()) {
1378 auto clientSp = i->getValue();
1379 if (clientSp.get() == client) {
1380 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001381 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001382 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001383}
1384
Ruben Brunkcc776712015-02-17 20:18:47 -08001385bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1386 const int callingPid = getCallingPid();
1387 const int servicePid = getpid();
1388 bool ret = false;
1389 {
1390 // Acquire mServiceLock and prevent other clients from connecting
1391 std::unique_ptr<AutoConditionLock> lock =
1392 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001393
Igor Murashkin634a5152013-02-20 17:15:11 -08001394
Ruben Brunkcc776712015-02-17 20:18:47 -08001395 std::vector<sp<BasicClient>> evicted;
1396 for (auto& i : mActiveClientManager.getAll()) {
1397 auto clientSp = i->getValue();
1398 if (clientSp.get() == nullptr) {
1399 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1400 mActiveClientManager.remove(i);
1401 continue;
1402 }
1403 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1404 callingPid == clientSp->getClientPid())) {
1405 mActiveClientManager.remove(i);
1406 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001407
Ruben Brunkcc776712015-02-17 20:18:47 -08001408 // Notify the client of disconnection
1409 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1410 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001411 }
1412 }
1413
Ruben Brunkcc776712015-02-17 20:18:47 -08001414 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1415 // other clients from connecting in mServiceLockWrapper if held
1416 mServiceLock.unlock();
1417
Ruben Brunk36597b22015-03-20 22:15:57 -07001418 // Do not clear caller identity, remote caller should be client proccess
1419
Ruben Brunkcc776712015-02-17 20:18:47 -08001420 for (auto& i : evicted) {
1421 if (i.get() != nullptr) {
1422 i->disconnect();
1423 ret = true;
1424 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001425 }
1426
Ruben Brunkcc776712015-02-17 20:18:47 -08001427 // Reacquire mServiceLock
1428 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001429
Ruben Brunkcc776712015-02-17 20:18:47 -08001430 } // lock is destroyed, allow further connect calls
1431
1432 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001433}
1434
Igor Murashkinecf17e82012-10-02 16:05:11 -07001435
Ruben Brunkcc776712015-02-17 20:18:47 -08001436std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1437 const String8& cameraId) const {
1438 std::shared_ptr<CameraState> state;
1439 {
1440 Mutex::Autolock lock(mCameraStatesLock);
1441 auto iter = mCameraStates.find(cameraId);
1442 if (iter != mCameraStates.end()) {
1443 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444 }
1445 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447}
1448
Ruben Brunkcc776712015-02-17 20:18:47 -08001449sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1450 // Remove from active clients list
1451 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1452 if (clientDescriptorPtr == nullptr) {
1453 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1454 cameraId.string());
1455 return sp<BasicClient>{nullptr};
1456 }
1457
1458 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001459}
1460
Ruben Brunk36597b22015-03-20 22:15:57 -07001461void CameraService::doUserSwitch(int newUserId) {
1462 // Acquire mServiceLock and prevent other clients from connecting
1463 std::unique_ptr<AutoConditionLock> lock =
1464 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1465
1466 if (newUserId <= 0) {
1467 ALOGW("%s: Bad user ID %d given during user switch, resetting to default.", __FUNCTION__,
1468 newUserId);
1469 newUserId = DEFAULT_LAST_USER_ID;
1470 }
1471
Ruben Brunka8ca9152015-04-07 14:23:40 -07001472 logUserSwitch(mLastUserId, newUserId);
1473
Ruben Brunk36597b22015-03-20 22:15:57 -07001474 mLastUserId = newUserId;
1475
1476 // Current user has switched, evict all current clients.
1477 std::vector<sp<BasicClient>> evicted;
1478 for (auto& i : mActiveClientManager.getAll()) {
1479 auto clientSp = i->getValue();
1480
1481 if (clientSp.get() == nullptr) {
1482 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1483 continue;
1484 }
1485
1486 evicted.push_back(clientSp);
1487
1488 String8 curTime = getFormattedCurrentTime();
1489
1490 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1491 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001492
Ruben Brunk36597b22015-03-20 22:15:57 -07001493 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001494 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001495 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001496 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1497 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001498
1499 }
1500
1501 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1502 // blocking other clients from connecting in mServiceLockWrapper if held.
1503 mServiceLock.unlock();
1504
1505 // Clear caller identity temporarily so client disconnect PID checks work correctly
1506 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1507
1508 for (auto& i : evicted) {
1509 i->disconnect();
1510 }
1511
1512 IPCThreadState::self()->restoreCallingIdentity(token);
1513
1514 // Reacquire mServiceLock
1515 mServiceLock.lock();
1516}
Ruben Brunkcc776712015-02-17 20:18:47 -08001517
Ruben Brunka8ca9152015-04-07 14:23:40 -07001518void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001519 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001520 Mutex::Autolock l(mLogLock);
1521 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522}
1523
Ruben Brunka8ca9152015-04-07 14:23:40 -07001524void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001525 const char* opPackageName) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001526 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001527 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001528 opPackageName, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001529}
1530
1531void CameraService::logConnected(const char* cameraId, int clientPid,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001532 const char* opPackageName) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001533 // Log the clients evicted
1534 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001535 opPackageName, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001536}
1537
1538void CameraService::logRejected(const char* cameraId, int clientPid,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001539 const char* opPackageName, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001540 // Log the client rejected
1541 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svet Ganov32fa6d02015-05-01 20:47:20 -07001542 cameraId, opPackageName, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001543}
1544
1545void CameraService::logUserSwitch(int oldUserId, int newUserId) {
1546 // Log the new and old users
1547 logEvent(String8::format("USER_SWITCH from old user: %d , to new user: %d", oldUserId,
1548 newUserId));
1549}
1550
1551void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1552 // Log the device removal
1553 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1554}
1555
1556void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1557 // Log the device removal
1558 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1559}
1560
1561void CameraService::logClientDied(int clientPid, const char* reason) {
1562 // Log the device removal
1563 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001564}
1565
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001566void CameraService::logServiceError(const char* msg, int errorCode) {
1567 String8 curTime = getFormattedCurrentTime();
1568 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1569}
1570
Ruben Brunk36597b22015-03-20 22:15:57 -07001571status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1572 uint32_t flags) {
1573
1574 const int pid = getCallingPid();
1575 const int selfPid = getpid();
1576
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 // Permission checks
1578 switch (code) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001579 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1580 if (pid != selfPid) {
1581 // Ensure we're being called by system_server, or similar process with
1582 // permissions to notify the camera service about system events
1583 if (!checkCallingPermission(
1584 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1585 const int uid = getCallingUid();
1586 ALOGE("Permission Denial: cannot send updates to camera service about system"
1587 " events from pid=%d, uid=%d", pid, uid);
1588 return PERMISSION_DENIED;
1589 }
1590 }
1591 break;
1592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 }
1594
1595 return BnCameraService::onTransact(code, data, reply, flags);
1596}
1597
Svet Ganov32fa6d02015-05-01 20:47:20 -07001598status_t CameraService::checkCameraAccess(const String16& opPackageName) {
1599 const int pid = getCallingPid();
1600
1601 if (pid == getpid()) {
1602 return NO_ERROR;
1603 }
1604
1605 const int uid = getCallingUid();
1606
1607 if (!checkCallingPermission(String16("android.permission.CAMERA"))) {
1608 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", pid, uid);
1609 return PERMISSION_DENIED;
1610 }
1611
1612 AppOpsManager appOps;
1613 const int32_t result = appOps.noteOp(AppOpsManager::OP_CAMERA, uid, opPackageName);
1614
1615 switch (result) {
1616 case AppOpsManager::MODE_ERRORED: {
1617 ALOGE("App op OP_CAMERA errored: can't use the camera pid=%d, uid=%d", pid, uid);
1618 return PERMISSION_DENIED;
1619 } break;
1620
1621 case AppOpsManager::MODE_IGNORED: {
1622 ALOGE("App op OP_CAMERA ignored: can't use the camera pid=%d, uid=%d", pid, uid);
1623 return INVALID_OPERATION;
1624 } break;
1625 }
1626
1627 return NO_ERROR;
1628}
1629
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630// We share the media players for shutter and recording sound for all clients.
1631// A reference count is kept to determine when we will actually release the
1632// media players.
1633
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001634MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001636 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001637 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 mp->prepare();
1639 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001640 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 return NULL;
1642 }
1643 return mp;
1644}
1645
1646void CameraService::loadSound() {
1647 Mutex::Autolock lock(mSoundLock);
1648 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1649 if (mSoundRef++) return;
1650
1651 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1652 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1653}
1654
1655void CameraService::releaseSound() {
1656 Mutex::Autolock lock(mSoundLock);
1657 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1658 if (--mSoundRef) return;
1659
1660 for (int i = 0; i < NUM_SOUNDS; i++) {
1661 if (mSoundPlayer[i] != 0) {
1662 mSoundPlayer[i]->disconnect();
1663 mSoundPlayer[i].clear();
1664 }
1665 }
1666}
1667
1668void CameraService::playSound(sound_kind kind) {
1669 LOG1("playSound(%d)", kind);
1670 Mutex::Autolock lock(mSoundLock);
1671 sp<MediaPlayer> player = mSoundPlayer[kind];
1672 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001673 player->seekTo(0);
1674 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 }
1676}
1677
1678// ----------------------------------------------------------------------------
1679
1680CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001681 const sp<ICameraClient>& cameraClient,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001682 const String16& opPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001683 int cameraId, int cameraFacing,
1684 int clientPid, uid_t clientUid,
1685 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001686 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001687 IInterface::asBinder(cameraClient),
Svet Ganov32fa6d02015-05-01 20:47:20 -07001688 opPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001689 cameraId, cameraFacing,
1690 clientPid, clientUid,
1691 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001692{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001694 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001696 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001699
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001700 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701}
1702
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703// tear down the client
1704CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001705 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001706 mDestructionStarted = true;
1707
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001708 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001709 // unconditionally disconnect. function is idempotent
1710 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711}
1712
Igor Murashkin634a5152013-02-20 17:15:11 -08001713CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001714 const sp<IBinder>& remoteCallback,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001715 const String16& opPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001716 int cameraId, int cameraFacing,
1717 int clientPid, uid_t clientUid,
1718 int servicePid):
Svet Ganov32fa6d02015-05-01 20:47:20 -07001719 mOpPackageName(opPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001720{
1721 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001722 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001723 mCameraId = cameraId;
1724 mCameraFacing = cameraFacing;
1725 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001726 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001727 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001728 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001729 mDestructionStarted = false;
1730}
1731
1732CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001733 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001734 mDestructionStarted = true;
1735}
1736
1737void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001738 if (mDisconnected) {
1739 ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1740 mCameraId);
1741 return;
1742 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001743 mDisconnected = true;;
1744
1745 mCameraService->removeByClient(this);
1746 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001747 String8(mOpPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001748
1749 sp<IBinder> remote = getRemote();
1750 if (remote != nullptr) {
1751 remote->unlinkToDeath(mCameraService);
1752 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001753
1754 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001755 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1756
Igor Murashkincba2c162013-03-20 15:56:31 -07001757 // client shouldn't be able to call into us anymore
1758 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001759}
1760
Ruben Brunkcc776712015-02-17 20:18:47 -08001761String16 CameraService::BasicClient::getPackageName() const {
Svet Ganov32fa6d02015-05-01 20:47:20 -07001762 return mOpPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001763}
1764
1765
1766int CameraService::BasicClient::getClientPid() const {
1767 return mClientPid;
1768}
1769
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001770bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1771 // Defaults to API2.
1772 return level == API_2;
1773}
1774
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001775status_t CameraService::BasicClient::startCameraOps() {
1776 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001777 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001778 mOpsCallback = new OpsCallback(this);
1779
Igor Murashkine6800ce2013-03-04 17:25:57 -08001780 {
1781 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svet Ganov32fa6d02015-05-01 20:47:20 -07001782 __FUNCTION__, String8(mOpPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001783 }
1784
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001785 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001786 mOpPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001787 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001788 mClientUid, mOpPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001789
1790 if (res != AppOpsManager::MODE_ALLOWED) {
1791 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svet Ganov32fa6d02015-05-01 20:47:20 -07001792 mCameraId, String8(mOpPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001793 return PERMISSION_DENIED;
1794 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001795
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001796 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001797
1798 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1799 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001800 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001801
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001802 return OK;
1803}
1804
1805status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001806 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001807 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001808 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001809 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001810 mOpPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001811 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001812
Ruben Brunkcc776712015-02-17 20:18:47 -08001813 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1814 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001815
Ruben Brunkcc776712015-02-17 20:18:47 -08001816 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001817 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001818 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001819
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001820 // Notify flashlight that a camera device is closed.
1821 mCameraService->mFlashlight->deviceClosed(
1822 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001823 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001824 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001825 if (mOpsCallback != NULL) {
1826 mAppOpsManager.stopWatchingMode(mOpsCallback);
1827 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001828 mOpsCallback.clear();
1829
1830 return OK;
1831}
1832
1833void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1834 String8 name(packageName);
Svet Ganov32fa6d02015-05-01 20:47:20 -07001835 String8 myName(mOpPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001836
1837 if (op != AppOpsManager::OP_CAMERA) {
1838 ALOGW("Unexpected app ops notification received: %d", op);
1839 return;
1840 }
1841
1842 int32_t res;
1843 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svet Ganov32fa6d02015-05-01 20:47:20 -07001844 mClientUid, mOpPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001845 ALOGV("checkOp returns: %d, %s ", res,
1846 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1847 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1848 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1849 "UNKNOWN");
1850
1851 if (res != AppOpsManager::MODE_ALLOWED) {
1852 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1853 myName.string());
1854 // Reset the client PID to allow server-initiated disconnect,
1855 // and to prevent further calls by client.
1856 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07001857 CaptureResultExtras resultExtras; // a dummy result (invalid)
1858 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001859 disconnect();
1860 }
1861}
1862
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863// ----------------------------------------------------------------------------
1864
Ruben Brunkcc776712015-02-17 20:18:47 -08001865// Provide client strong pointer for callbacks.
1866sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
1867 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
1868 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
1869 if (clientDescriptor != nullptr) {
1870 return sp<Client>{
1871 static_cast<Client*>(clientDescriptor->getValue().get())};
1872 }
1873 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874}
1875
Jianing Weicb0652e2014-03-12 18:29:36 -07001876void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1877 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001878 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001879}
1880
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001881// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07001882void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001883 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08001884 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08001885}
1886
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001887bool CameraService::Client::canCastToApiClient(apiLevel level) const {
1888 return level == API_1;
1889}
1890
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001891CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1892 mClient(client) {
1893}
1894
1895void CameraService::Client::OpsCallback::opChanged(int32_t op,
1896 const String16& packageName) {
1897 sp<BasicClient> client = mClient.promote();
1898 if (client != NULL) {
1899 client->opChanged(op, packageName);
1900 }
1901}
1902
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08001904// CameraState
1905// ----------------------------------------------------------------------------
1906
1907CameraService::CameraState::CameraState(const String8& id, int cost,
1908 const std::set<String8>& conflicting) : mId(id),
1909 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
1910
1911CameraService::CameraState::~CameraState() {}
1912
1913ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
1914 Mutex::Autolock lock(mStatusLock);
1915 return mStatus;
1916}
1917
1918CameraParameters CameraService::CameraState::getShimParams() const {
1919 return mShimParams;
1920}
1921
1922void CameraService::CameraState::setShimParams(const CameraParameters& params) {
1923 mShimParams = params;
1924}
1925
1926int CameraService::CameraState::getCost() const {
1927 return mCost;
1928}
1929
1930std::set<String8> CameraService::CameraState::getConflicting() const {
1931 return mConflicting;
1932}
1933
1934String8 CameraService::CameraState::getId() const {
1935 return mId;
1936}
1937
1938// ----------------------------------------------------------------------------
1939// CameraClientManager
1940// ----------------------------------------------------------------------------
1941
1942CameraService::CameraClientManager::~CameraClientManager() {}
1943
1944sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
1945 const String8& id) const {
1946 auto descriptor = get(id);
1947 if (descriptor == nullptr) {
1948 return sp<BasicClient>{nullptr};
1949 }
1950 return descriptor->getValue();
1951}
1952
1953String8 CameraService::CameraClientManager::toString() const {
1954 auto all = getAll();
1955 String8 ret("[");
1956 bool hasAny = false;
1957 for (auto& i : all) {
1958 hasAny = true;
1959 String8 key = i->getKey();
1960 int32_t cost = i->getCost();
1961 int32_t pid = i->getOwnerId();
1962 int32_t priority = i->getPriority();
1963 auto conflicting = i->getConflicting();
1964 auto clientSp = i->getValue();
1965 String8 packageName;
1966 if (clientSp.get() != nullptr) {
1967 packageName = String8{clientSp->getPackageName()};
1968 }
1969 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
1970 PRId32 ", ", key.string(), cost, pid, priority);
1971
1972 if (packageName.size() != 0) {
1973 ret.appendFormat("Client Package Name: %s", packageName.string());
1974 }
1975
1976 ret.append(", Conflicting Client Devices: {");
1977 for (auto& j : conflicting) {
1978 ret.appendFormat("%s, ", j.string());
1979 }
1980 ret.append("})");
1981 }
1982 if (hasAny) ret.append("\n");
1983 ret.append("]\n");
1984 return ret;
1985}
1986
1987CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1988 const String8& key, const sp<BasicClient>& value, int32_t cost,
1989 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
1990
1991 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
1992 key, value, cost, conflictingKeys, priority, ownerId);
1993}
1994
1995CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1996 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
1997 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
1998 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
1999}
2000
2001// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002
2003static const int kDumpLockRetries = 50;
2004static const int kDumpLockSleep = 60000;
2005
2006static bool tryLock(Mutex& mutex)
2007{
2008 bool locked = false;
2009 for (int i = 0; i < kDumpLockRetries; ++i) {
2010 if (mutex.tryLock() == NO_ERROR) {
2011 locked = true;
2012 break;
2013 }
2014 usleep(kDumpLockSleep);
2015 }
2016 return locked;
2017}
2018
2019status_t CameraService::dump(int fd, const Vector<String16>& args) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002020 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002022 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 "can't dump CameraService from pid=%d, uid=%d\n",
2024 getCallingPid(),
2025 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 write(fd, result.string(), result.size());
2027 } else {
2028 bool locked = tryLock(mServiceLock);
2029 // failed to lock - CameraService is probably deadlocked
2030 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002031 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002032 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 }
2034
2035 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002036 if (!mModule) {
2037 result = String8::format("No camera module available!\n");
2038 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002039
2040 // Dump event log for error information
2041 dumpEventLog(fd);
2042
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002043 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002044 return NO_ERROR;
2045 }
2046
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002047 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2048 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2049 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2050 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002051 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2052 String8 activeClientString = mActiveClientManager.toString();
2053 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2054
Ruben Brunkf81648e2014-04-17 16:14:57 -07002055 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2056 if (desc == NULL) {
2057 result.appendFormat("Vendor tags left unimplemented.\n");
2058 } else {
2059 result.appendFormat("Vendor tag definitions:\n");
2060 }
2061
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002062 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002063
2064 if (desc != NULL) {
2065 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2066 }
2067
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002068 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002069
2070 bool stateLocked = tryLock(mCameraStatesLock);
2071 if (!stateLocked) {
2072 result = String8::format("CameraStates in use, may be deadlocked\n");
2073 write(fd, result.string(), result.size());
2074 }
2075
2076 for (auto& state : mCameraStates) {
2077 String8 cameraId = state.first;
2078 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002079 camera_info info;
2080
Ruben Brunkcc776712015-02-17 20:18:47 -08002081 // TODO: Change getCameraInfo + HAL to use String cameraIds
2082 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002083 if (rc != OK) {
2084 result.appendFormat(" Error reading static information!\n");
2085 write(fd, result.string(), result.size());
2086 } else {
2087 result.appendFormat(" Facing: %s\n",
2088 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2089 result.appendFormat(" Orientation: %d\n", info.orientation);
2090 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002091 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002092 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2093 } else {
2094 deviceVersion = info.device_version;
2095 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002096
2097 auto conflicting = state.second->getConflicting();
2098 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2099 result.appendFormat(" Conflicting Devices:");
2100 for (auto& id : conflicting) {
2101 result.appendFormat(" %s", cameraId.string());
2102 }
2103 if (conflicting.size() == 0) {
2104 result.appendFormat(" NONE");
2105 }
2106 result.appendFormat("\n");
2107
2108 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002109 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2110 result.appendFormat(" Device static metadata:\n");
2111 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002112 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002113 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002114 } else {
2115 write(fd, result.string(), result.size());
2116 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002117
2118 CameraParameters p = state.second->getShimParams();
2119 if (!p.isEmpty()) {
2120 result = String8::format(" Camera1 API shim is using parameters:\n ");
2121 write(fd, result.string(), result.size());
2122 p.dump(fd, args);
2123 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002124 }
2125
Ruben Brunkcc776712015-02-17 20:18:47 -08002126 auto clientDescriptor = mActiveClientManager.get(cameraId);
2127 if (clientDescriptor == nullptr) {
2128 result = String8::format(" Device %s is closed, no client instance\n",
2129 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002130 write(fd, result.string(), result.size());
2131 continue;
2132 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002134 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2135 cameraId.string());
2136 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2137 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2138
2139 auto client = clientDescriptor->getValue();
2140 result.appendFormat("Client package: %s\n",
2141 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002142 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002143
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002144 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002146
2147 if (stateLocked) mCameraStatesLock.unlock();
2148
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002150 result = String8::format("\nNo active camera clients yet.\n");
2151 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 }
2153
2154 if (locked) mServiceLock.unlock();
2155
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002156 // Dump camera traces if there were any
2157 write(fd, "\n", 1);
2158 camera3::CameraTraces::dump(fd, args);
2159
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160 // change logging level
2161 int n = args.size();
2162 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002163 String16 verboseOption("-v");
2164 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 String8 levelStr(args[i+1]);
2166 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002167 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002169 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170 }
2171 }
2172 }
2173 return NO_ERROR;
2174}
2175
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002176void CameraService::dumpEventLog(int fd) {
2177 String8 result = String8("\nPrior client events (most recent at top):\n");
2178
2179 Mutex::Autolock l(mLogLock);
2180 for (const auto& msg : mEventLog) {
2181 result.appendFormat(" %s\n", msg.string());
2182 }
2183
2184 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2185 result.append(" ...\n");
2186 } else if (mEventLog.size() == 0) {
2187 result.append(" [no events yet]\n");
2188 }
2189 result.append("\n");
2190
2191 write(fd, result.string(), result.size());
2192}
2193
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002194void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002195 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002196 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2197 if (mTorchClientMap[i] == who) {
2198 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002199 String8 cameraId = mTorchClientMap.keyAt(i);
2200 status_t res = mFlashlight->setTorchMode(cameraId, false);
2201 if (res) {
2202 ALOGE("%s: torch client died but couldn't turn off torch: "
2203 "%s (%d)", __FUNCTION__, strerror(-res), res);
2204 return;
2205 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002206 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002207 break;
2208 }
2209 }
2210}
2211
Ruben Brunkcc776712015-02-17 20:18:47 -08002212/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002213
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002214 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002215 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2216 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002217 */
2218
Ruben Brunka8ca9152015-04-07 14:23:40 -07002219 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2220
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002221 // check torch client
2222 handleTorchClientBinderDied(who);
2223
2224 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002225 if(!evictClientIdByRemote(who)) {
2226 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002227 return;
2228 }
2229
Ruben Brunkcc776712015-02-17 20:18:47 -08002230 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2231 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002232}
2233
Ruben Brunkcc776712015-02-17 20:18:47 -08002234void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2235 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002236}
2237
Ruben Brunkcc776712015-02-17 20:18:47 -08002238void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2239 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2240 // Do not lock mServiceLock here or can get into a deadlock from
2241 // connect() -> disconnect -> updateStatus
2242
2243 auto state = getCameraState(cameraId);
2244
2245 if (state == nullptr) {
2246 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2247 cameraId.string());
2248 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002249 }
2250
Ruben Brunkcc776712015-02-17 20:18:47 -08002251 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2252 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2253 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2254 (const String8& cameraId, ICameraServiceListener::Status status) {
2255
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002256 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2257 // Update torch status if it has a flash unit.
2258 Mutex::Autolock al(mTorchStatusMutex);
2259 ICameraServiceListener::TorchStatus torchStatus;
2260 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2261 NAME_NOT_FOUND) {
2262 ICameraServiceListener::TorchStatus newTorchStatus =
2263 status == ICameraServiceListener::STATUS_PRESENT ?
2264 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2265 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2266 if (torchStatus != newTorchStatus) {
2267 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2268 }
2269 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002270 }
2271
2272 Mutex::Autolock lock(mStatusListenerLock);
2273
2274 for (auto& listener : mListenerList) {
2275 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2276 int id = cameraIdToInt(cameraId);
2277 if (id != -1) listener->onStatusChanged(status, id);
2278 }
2279 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002280}
2281
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002282status_t CameraService::getTorchStatusLocked(
2283 const String8& cameraId,
2284 ICameraServiceListener::TorchStatus *status) const {
2285 if (!status) {
2286 return BAD_VALUE;
2287 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002288 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2289 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002290 // invalid camera ID or the camera doesn't have a flash unit
2291 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002292 }
2293
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002294 *status = mTorchStatusMap.valueAt(index);
2295 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002296}
2297
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002298status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002299 ICameraServiceListener::TorchStatus status) {
2300 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2301 if (index == NAME_NOT_FOUND) {
2302 return BAD_VALUE;
2303 }
2304 ICameraServiceListener::TorchStatus& item =
2305 mTorchStatusMap.editValueAt(index);
2306 item = status;
2307
2308 return OK;
2309}
2310
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311}; // namespace android