blob: 574165bb83d5f9d9416c6bcd1a913b829bd6fbe6 [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>
Amith Yamasani228711d2015-02-13 13:25:39 -080038#include <cutils/multiuser.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080039#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <hardware/hardware.h>
41#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080042#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <media/mediaplayer.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <utils/Errors.h>
45#include <utils/Log.h>
46#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080047#include <utils/Trace.h>
48#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070049#include <system/camera_metadata.h>
50#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
52#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "api1/CameraClient.h"
54#include "api1/Camera2Client.h"
55#include "api_pro/ProCamera2Client.h"
56#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070057#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070058#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
60namespace android {
61
62// ----------------------------------------------------------------------------
63// Logging support -- this is for debugging only
64// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070065volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Steve Blockb8a80522011-12-20 16:23:08 +000067#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
70static void setLogLevel(int level) {
71 android_atomic_write(level, &gLogLevel);
72}
73
74// ----------------------------------------------------------------------------
75
Igor Murashkincba2c162013-03-20 15:56:31 -070076extern "C" {
77static void camera_device_status_change(
78 const struct camera_module_callbacks* callbacks,
79 int camera_id,
80 int new_status) {
81 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080082 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070083
Ruben Brunkcc776712015-02-17 20:18:47 -080084 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
85 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070086}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080087
88static void torch_mode_status_change(
89 const struct camera_module_callbacks* callbacks,
90 const char* camera_id,
91 int new_status) {
92 if (!callbacks || !camera_id) {
93 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
94 callbacks, camera_id);
95 }
96 sp<CameraService> cs = const_cast<CameraService*>(
97 static_cast<const CameraService*>(callbacks));
98
99 ICameraServiceListener::TorchStatus status;
100 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800101 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800102 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
103 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800104 case TORCH_MODE_STATUS_AVAILABLE_OFF:
105 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
106 break;
107 case TORCH_MODE_STATUS_AVAILABLE_ON:
108 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800109 break;
110 default:
111 ALOGE("Unknown torch status %d", new_status);
112 return;
113 }
114
115 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800116 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800117 status);
118}
Igor Murashkincba2c162013-03-20 15:56:31 -0700119} // extern "C"
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
123// This is ugly and only safe if we never re-create the CameraService, but
124// should be ok for now.
125static CameraService *gCameraService;
126
127CameraService::CameraService()
Ruben Brunkcc776712015-02-17 20:18:47 -0800128 : mEventLog(DEFAULT_EVICTION_LOG_LENGTH), mSoundRef(0), mModule(0), mFlashlight(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129{
Steve Blockdf64d152012-01-04 20:05:49 +0000130 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800132
Igor Murashkincba2c162013-03-20 15:56:31 -0700133 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800134 this->torch_mode_status_change = android::torch_mode_status_change;
135
Ruben Brunkcc776712015-02-17 20:18:47 -0800136 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137}
138
Iliyan Malchev8951a972011-04-14 16:55:59 -0700139void CameraService::onFirstRef()
140{
Ruben Brunkcc776712015-02-17 20:18:47 -0800141 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800142
Iliyan Malchev8951a972011-04-14 16:55:59 -0700143 BnCameraService::onFirstRef();
144
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800145 camera_module_t *rawModule;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700146 if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800147 (const hw_module_t **)&rawModule) < 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000148 ALOGE("Could not load camera HAL module");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700149 mNumberOfCameras = 0;
150 }
151 else {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800152 mModule = new CameraModule(rawModule);
153 const hw_module_t *common = mModule->getRawModule();
Ruben Brunkcc776712015-02-17 20:18:47 -0800154 ALOGI("Loaded \"%s\" camera module", common->name);
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800155 mNumberOfCameras = mModule->getNumberOfCameras();
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800156
157 mFlashlight = new CameraFlashlight(*mModule, *this);
158 status_t res = mFlashlight->findFlashUnits();
159 if (res) {
160 // impossible because we haven't open any camera devices.
Ruben Brunkcc776712015-02-17 20:18:47 -0800161 ALOGE("Failed to find flash units.");
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800162 }
163
Iliyan Malchev8951a972011-04-14 16:55:59 -0700164 for (int i = 0; i < mNumberOfCameras; i++) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800165 String8 cameraId = String8::format("%d", i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800166
Ruben Brunkcc776712015-02-17 20:18:47 -0800167 // Defaults to use for cost and conflicting devices
168 int cost = 100;
169 char** conflicting_devices = nullptr;
170 size_t conflicting_devices_length = 0;
171
172 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
173 if (common->module_api_version >= CAMERA_MODULE_API_VERSION_2_4) {
174 struct camera_info info;
175 status_t rc = mModule->getCameraInfo(i, &info);
176 if (rc == NO_ERROR) {
177 cost = info.resource_cost;
178 conflicting_devices = info.conflicting_devices;
179 conflicting_devices_length = info.conflicting_devices_length;
180 } else {
181 ALOGE("%s: Received error loading camera info for device %d, cost and"
182 " conflicting devices fields set to defaults for this device.",
183 __FUNCTION__, i);
184 }
185 }
186
187 std::set<String8> conflicting;
188 for (size_t i = 0; i < conflicting_devices_length; i++) {
189 conflicting.emplace(String8(conflicting_devices[i]));
190 }
191
192 // Initialize state for each camera device
193 {
194 Mutex::Autolock lock(mCameraStatesLock);
195 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
196 conflicting));
197 }
198
199 if (mFlashlight->hasFlashUnit(cameraId)) {
200 mTorchStatusMap.add(cameraId,
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800201 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800202 }
Iliyan Malchev8951a972011-04-14 16:55:59 -0700203 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700204
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800205 if (common->module_api_version >= CAMERA_MODULE_API_VERSION_2_1) {
206 mModule->setCallbacks(this);
Igor Murashkincba2c162013-03-20 15:56:31 -0700207 }
Igor Murashkin98e24722013-06-19 19:51:04 -0700208
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800209 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
210
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800211 if (common->module_api_version >= CAMERA_MODULE_API_VERSION_2_2) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800212 setUpVendorTags();
213 }
214
Igor Murashkin98e24722013-06-19 19:51:04 -0700215 CameraDeviceFactory::registerService(this);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700216 }
217}
218
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800220 if (mModule) {
221 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800222 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800223 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800224 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800225 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226}
227
Ruben Brunkcc776712015-02-17 20:18:47 -0800228void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
229 camera_device_status_t newStatus) {
230 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700231 cameraId, newStatus);
232
Ruben Brunkcc776712015-02-17 20:18:47 -0800233 String8 id = String8::format("%d", cameraId);
234 std::shared_ptr<CameraState> state = getCameraState(id);
235
236 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700237 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
238 return;
239 }
240
Ruben Brunkcc776712015-02-17 20:18:47 -0800241 ICameraServiceListener::Status oldStatus = state->getStatus();
242
243 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
244 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700245 return;
246 }
247
Igor Murashkincba2c162013-03-20 15:56:31 -0700248 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800249 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700250 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800251 // Don't do this in updateStatus to avoid deadlock over mServiceLock
252 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700253
Ruben Brunkcc776712015-02-17 20:18:47 -0800254 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
255 // to this device until the status changes
256 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700257
Ruben Brunkcc776712015-02-17 20:18:47 -0800258 // Remove cached shim parameters
259 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700260
Ruben Brunkcc776712015-02-17 20:18:47 -0800261 // Remove the client from the list of active clients
262 clientToDisconnect = removeClientLocked(id);
263
264 // Notify the client of disconnection
265 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
266 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700267 }
268
Ruben Brunkcc776712015-02-17 20:18:47 -0800269 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
270 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700271
Ruben Brunkcc776712015-02-17 20:18:47 -0800272 // Disconnect client
273 if (clientToDisconnect.get() != nullptr) {
274 // Ensure not in binder RPC so client disconnect PID checks work correctly
275 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
276 "onDeviceStatusChanged must be called from the camera service process!");
277 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700278 }
279
Ruben Brunkcc776712015-02-17 20:18:47 -0800280 } else {
281 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700282 }
283
Igor Murashkincba2c162013-03-20 15:56:31 -0700284}
285
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800286void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800287 ICameraServiceListener::TorchStatus newStatus) {
288 Mutex::Autolock al(mTorchStatusMutex);
289 onTorchStatusChangedLocked(cameraId, newStatus);
290}
291
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800292void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800293 ICameraServiceListener::TorchStatus newStatus) {
294 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
295 __FUNCTION__, cameraId.string(), newStatus);
296
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800297 ICameraServiceListener::TorchStatus status;
298 status_t res = getTorchStatusLocked(cameraId, &status);
299 if (res) {
300 ALOGE("%s: cannot get torch status of camera %s", cameraId.string());
301 return;
302 }
303 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800304 ALOGE("%s: Torch state transition to the same status 0x%x not allowed",
305 __FUNCTION__, (uint32_t)newStatus);
306 return;
307 }
308
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800309 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800310 if (res) {
311 ALOGE("%s: Failed to set the torch status", __FUNCTION__,
312 (uint32_t)newStatus);
313 return;
314 }
315
Ruben Brunkcc776712015-02-17 20:18:47 -0800316 {
317 Mutex::Autolock lock(mStatusListenerLock);
318 for (auto& i : mListenerList) {
319 i->onTorchStatusChanged(newStatus, String16{cameraId});
320 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800321 }
322}
323
324
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325int32_t CameraService::getNumberOfCameras() {
326 return mNumberOfCameras;
327}
328
329status_t CameraService::getCameraInfo(int cameraId,
330 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700331 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700332 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700333 }
334
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
336 return BAD_VALUE;
337 }
338
Iliyan Malchev8951a972011-04-14 16:55:59 -0700339 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700340 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800341 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700342 cameraInfo->facing = info.facing;
343 cameraInfo->orientation = info.orientation;
344 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345}
346
Ruben Brunkcc776712015-02-17 20:18:47 -0800347int CameraService::cameraIdToInt(const String8& cameraId) {
348 errno = 0;
349 size_t pos = 0;
350 int ret = stoi(std::string{cameraId.string()}, &pos);
351 if (errno != 0 || pos != cameraId.size()) {
352 return -1;
353 }
354 return ret;
355}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700356
357status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
358 status_t ret = OK;
359 struct CameraInfo info;
360 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
361 return ret;
362 }
363
364 CameraMetadata shimInfo;
365 int32_t orientation = static_cast<int32_t>(info.orientation);
366 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
367 return ret;
368 }
369
370 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
371 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
372 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
373 return ret;
374 }
375
Igor Murashkin65d14b92014-06-17 12:03:20 -0700376 CameraParameters shimParams;
377 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
378 // Error logged by callee
379 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700380 }
381
382 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700383 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700384 Vector<int32_t> formats;
385 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700386 {
387 shimParams.getSupportedPreviewSizes(/*out*/sizes);
388 shimParams.getSupportedPreviewFormats(/*out*/formats);
389 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700390 }
391
392 // Always include IMPLEMENTATION_DEFINED
393 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
394
395 const size_t INTS_PER_CONFIG = 4;
396
397 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700398 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
399
400 Vector<int32_t> streamConfigs;
401 streamConfigs.setCapacity(streamConfigSize);
402
Ruben Brunkb2119af2014-05-09 19:57:56 -0700403 for (size_t i = 0; i < formats.size(); ++i) {
404 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700405 streamConfigs.add(formats[i]);
406 streamConfigs.add(sizes[j].width);
407 streamConfigs.add(sizes[j].height);
408 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700409 }
410 }
411
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700412 for (size_t i = 0; i < jpegSizes.size(); ++i) {
413 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
414 streamConfigs.add(jpegSizes[i].width);
415 streamConfigs.add(jpegSizes[i].height);
416 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
417 }
418
Ruben Brunkb2119af2014-05-09 19:57:56 -0700419 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700420 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700421 return ret;
422 }
423
424 int64_t fakeMinFrames[0];
425 // TODO: Fixme, don't fake min frame durations.
426 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
427 fakeMinFrames, 0)) != OK) {
428 return ret;
429 }
430
431 int64_t fakeStalls[0];
432 // TODO: Fixme, don't fake stall durations.
433 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
434 fakeStalls, 0)) != OK) {
435 return ret;
436 }
437
438 *cameraInfo = shimInfo;
439 return OK;
440}
441
Zhijun He2b59be82013-09-25 10:14:30 -0700442status_t CameraService::getCameraCharacteristics(int cameraId,
443 CameraMetadata* cameraInfo) {
444 if (!cameraInfo) {
445 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
446 return BAD_VALUE;
447 }
448
449 if (!mModule) {
450 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
451 return -ENODEV;
452 }
453
Zhijun He2b59be82013-09-25 10:14:30 -0700454 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
455 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
456 return BAD_VALUE;
457 }
458
459 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700460 status_t ret = OK;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800461 if (mModule->getRawModule()->module_api_version < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700462 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
463 /**
464 * Backwards compatibility mode for old HALs:
465 * - Convert CameraInfo into static CameraMetadata properties.
466 * - Retrieve cached CameraParameters for this camera. If none exist,
467 * attempt to open CameraClient and retrieve the CameraParameters.
468 * - Convert cached CameraParameters into static CameraMetadata
469 * properties.
470 */
471 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700472
Ruben Brunkb2119af2014-05-09 19:57:56 -0700473 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
474 return ret;
475 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700476
Ruben Brunkb2119af2014-05-09 19:57:56 -0700477 } else {
478 /**
479 * Normal HAL 2.1+ codepath.
480 */
481 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800482 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700483 *cameraInfo = info.static_camera_characteristics;
484 }
Zhijun He2b59be82013-09-25 10:14:30 -0700485
486 return ret;
487}
488
Ruben Brunkcc776712015-02-17 20:18:47 -0800489int CameraService::getCallingPid() {
490 return IPCThreadState::self()->getCallingPid();
491}
492
493int CameraService::getCallingUid() {
494 return IPCThreadState::self()->getCallingUid();
495}
496
497String8 CameraService::getFormattedCurrentTime() {
498 time_t now = time(nullptr);
499 char formattedTime[64];
500 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
501 return String8(formattedTime);
502}
503
504int CameraService::getCameraPriorityFromProcState(int procState) {
505 // Find the priority for the camera usage based on the process state. Higher priority clients
506 // win for evictions.
507 // Note: Unlike the ordering for ActivityManager, persistent system processes will always lose
508 // the camera to the top/foreground applications.
509 switch(procState) {
510 case PROCESS_STATE_TOP: // User visible
511 return 100;
512 case PROCESS_STATE_IMPORTANT_FOREGROUND: // Foreground
513 return 90;
514 case PROCESS_STATE_PERSISTENT: // Persistent system services
515 case PROCESS_STATE_PERSISTENT_UI:
516 return 80;
517 case PROCESS_STATE_IMPORTANT_BACKGROUND: // "Important" background processes
518 return 70;
519 case PROCESS_STATE_BACKUP: // Everything else
520 case PROCESS_STATE_HEAVY_WEIGHT:
521 case PROCESS_STATE_SERVICE:
522 case PROCESS_STATE_RECEIVER:
523 case PROCESS_STATE_HOME:
524 case PROCESS_STATE_LAST_ACTIVITY:
525 case PROCESS_STATE_CACHED_ACTIVITY:
526 case PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
527 case PROCESS_STATE_CACHED_EMPTY:
528 return 1;
529 case PROCESS_STATE_NONEXISTENT:
530 return -1;
531 default:
532 ALOGE("%s: Received unknown process state from ActivityManagerService!", __FUNCTION__);
533 return -1;
534 }
535}
536
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800537status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
538 if (!mModule) {
539 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
540 return -ENODEV;
541 }
542
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800543 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
544 return OK;
545}
546
Igor Murashkin634a5152013-02-20 17:15:11 -0800547int CameraService::getDeviceVersion(int cameraId, int* facing) {
548 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800549 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800550 return -1;
551 }
552
553 int deviceVersion;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800554 if (mModule->getRawModule()->module_api_version >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800555 deviceVersion = info.device_version;
556 } else {
557 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
558 }
559
560 if (facing) {
561 *facing = info.facing;
562 }
563
564 return deviceVersion;
565}
566
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700567status_t CameraService::filterGetInfoErrorCode(status_t err) {
568 switch(err) {
569 case NO_ERROR:
570 case -EINVAL:
571 return err;
572 default:
573 break;
574 }
575 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800576}
577
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800578bool CameraService::setUpVendorTags() {
579 vendor_tag_ops_t vOps = vendor_tag_ops_t();
580
581 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800582 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800583 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
584 return false;
585 }
586
587 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800588 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800589 ATRACE_END();
590
591 // Ensure all vendor operations are present
592 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
593 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
594 vOps.get_tag_type == NULL) {
595 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
596 , __FUNCTION__);
597 return false;
598 }
599
600 // Read all vendor tag definitions into a descriptor
601 sp<VendorTagDescriptor> desc;
602 status_t res;
603 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
604 != OK) {
605 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
606 "received error %s (%d). Camera clients will not be able to use"
607 "vendor tags", __FUNCTION__, strerror(res), res);
608 return false;
609 }
610
611 // Set the global descriptor to use with camera metadata
612 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
613 return true;
614}
615
Ruben Brunkcc776712015-02-17 20:18:47 -0800616status_t CameraService::makeClient(const sp<CameraService>& cameraService,
617 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
618 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
619 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
620 /*out*/sp<BasicClient>* client) {
621
622 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
623 int id = cameraIdToInt(cameraId);
624 if (id == -1) {
625 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
626 cameraId.string());
627 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700628 }
629
Ruben Brunkcc776712015-02-17 20:18:47 -0800630 if (halVersion < 0 || halVersion == deviceVersion) {
631 // Default path: HAL version is unspecified by caller, create CameraClient
632 // based on device version reported by the HAL.
633 switch(deviceVersion) {
634 case CAMERA_DEVICE_API_VERSION_1_0:
635 if (effectiveApiLevel == API_1) { // Camera1 API route
636 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
637 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
638 clientPid, clientUid, getpid(), legacyMode);
639 } else { // Camera2 API route
640 ALOGW("Camera using old HAL version: %d", deviceVersion);
641 return -EOPNOTSUPP;
642 }
643 break;
644 case CAMERA_DEVICE_API_VERSION_2_0:
645 case CAMERA_DEVICE_API_VERSION_2_1:
646 case CAMERA_DEVICE_API_VERSION_3_0:
647 case CAMERA_DEVICE_API_VERSION_3_1:
648 case CAMERA_DEVICE_API_VERSION_3_2:
649 case CAMERA_DEVICE_API_VERSION_3_3:
650 if (effectiveApiLevel == API_1) { // Camera1 API route
651 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
652 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
653 clientPid, clientUid, servicePid, legacyMode);
654 } else { // Camera2 API route
655 sp<ICameraDeviceCallbacks> tmp =
656 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
657 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
658 facing, clientPid, clientUid, servicePid);
659 }
660 break;
661 default:
662 // Should not be reachable
663 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
664 return INVALID_OPERATION;
665 }
666 } else {
667 // A particular HAL version is requested by caller. Create CameraClient
668 // based on the requested HAL version.
669 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
670 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
671 // Only support higher HAL version device opened as HAL1.0 device.
672 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
673 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
674 clientPid, clientUid, servicePid, legacyMode);
675 } else {
676 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
677 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
678 " opened as HAL %x device", halVersion, deviceVersion,
679 CAMERA_DEVICE_API_VERSION_1_0);
680 return INVALID_OPERATION;
681 }
682 }
683 return NO_ERROR;
684}
685
686status_t CameraService::initializeShimMetadata(int cameraId) {
687 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700688
689 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800690 String8 id = String8::format("%d", cameraId);
691 status_t ret = NO_ERROR;
692 sp<Client> tmp = nullptr;
693 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
694 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
695 false, true, tmp)) != NO_ERROR) {
696 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
697 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700698 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800699 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700700}
701
Igor Murashkin65d14b92014-06-17 12:03:20 -0700702status_t CameraService::getLegacyParametersLazy(int cameraId,
703 /*out*/
704 CameraParameters* parameters) {
705
706 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
707
708 status_t ret = 0;
709
710 if (parameters == NULL) {
711 ALOGE("%s: parameters must not be null", __FUNCTION__);
712 return BAD_VALUE;
713 }
714
Ruben Brunkcc776712015-02-17 20:18:47 -0800715 String8 id = String8::format("%d", cameraId);
716
717 // Check if we already have parameters
718 {
719 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700720 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800721 auto cameraState = getCameraState(id);
722 if (cameraState == nullptr) {
723 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
724 return BAD_VALUE;
725 }
726 CameraParameters p = cameraState->getShimParams();
727 if (!p.isEmpty()) {
728 *parameters = p;
729 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700730 }
731 }
732
Ruben Brunkcc776712015-02-17 20:18:47 -0800733 int64_t token = IPCThreadState::self()->clearCallingIdentity();
734 ret = initializeShimMetadata(cameraId);
735 IPCThreadState::self()->restoreCallingIdentity(token);
736 if (ret != NO_ERROR) {
737 // Error already logged by callee
738 return ret;
739 }
740
741 // Check for parameters again
742 {
743 // Scope for service lock
744 Mutex::Autolock lock(mServiceLock);
745 auto cameraState = getCameraState(id);
746 if (cameraState == nullptr) {
747 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
748 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700749 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800750 CameraParameters p = cameraState->getShimParams();
751 if (!p.isEmpty()) {
752 *parameters = p;
753 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700754 }
755 }
756
Ruben Brunkcc776712015-02-17 20:18:47 -0800757 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
758 __FUNCTION__);
759 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700760}
761
Ruben Brunkcc776712015-02-17 20:18:47 -0800762status_t CameraService::validateConnect(const String8& cameraId, /*inout*/int& clientUid) const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800763
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500765
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800766 if (clientUid == USE_CALLING_UID) {
767 clientUid = getCallingUid();
768 } else {
769 // We only trust our own process to forward client UIDs
770 if (callingPid != getpid()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800771 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid)",
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800772 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700773 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800774 }
775 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700776
Iliyan Malchev8951a972011-04-14 16:55:59 -0700777 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800778 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
779 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700780 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700781 }
782
Ruben Brunkcc776712015-02-17 20:18:47 -0800783 if (getCameraState(cameraId) == nullptr) {
784 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
785 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700786 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 }
788
Ruben Brunkcc776712015-02-17 20:18:47 -0800789 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800790 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800791 char key[PROPERTY_KEY_MAX];
792 int clientUserId = multiuser_get_user_id(clientUid);
793 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
794 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800795 if (strcmp(value, "1") == 0) {
796 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800797 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
798 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700799 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800800 }
801
Ruben Brunkcc776712015-02-17 20:18:47 -0800802 return checkIfDeviceIsUsable(cameraId);
803}
804
805status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
806 auto cameraState = getCameraState(cameraId);
807 int callingPid = getCallingPid();
808 if (cameraState == nullptr) {
809 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
810 cameraId.string());
811 return -ENODEV;
812 }
813
814 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700815 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800816 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
817 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700818 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700819 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
821 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700822 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700823 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700824
Ruben Brunkcc776712015-02-17 20:18:47 -0800825 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800826}
827
Ruben Brunkcc776712015-02-17 20:18:47 -0800828void CameraService::finishConnectLocked(const sp<BasicClient>& client,
829 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800830
Ruben Brunkcc776712015-02-17 20:18:47 -0800831 // Make a descriptor for the incoming client
832 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
833 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
834
835 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
836 String8(client->getPackageName()));
837
838 if (evicted.size() > 0) {
839 // This should never happen - clients should already have been removed in disconnect
840 for (auto& i : evicted) {
841 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
842 __FUNCTION__, i->getKey().string());
843 }
844
845 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
846 __FUNCTION__);
847 }
848}
849
850status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
851 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
852 /*out*/
853 sp<BasicClient>* client,
854 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
855
856 status_t ret = NO_ERROR;
857 std::vector<sp<BasicClient>> evictedClients;
858 DescriptorPtr clientDescriptor;
859 {
860 if (effectiveApiLevel == API_1) {
861 // If we are using API1, any existing client for this camera ID with the same remote
862 // should be returned rather than evicted to allow MediaRecorder to work properly.
863
864 auto current = mActiveClientManager.get(cameraId);
865 if (current != nullptr) {
866 auto clientSp = current->getValue();
867 if (clientSp.get() != nullptr) { // should never be needed
868 if (clientSp->getRemote() == remoteCallback) {
869 ALOGI("CameraService::connect X (PID %d) (second call from same"
870 "app binder, returning the same client)", clientPid);
871 *client = clientSp;
872 return NO_ERROR;
873 }
874 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800875 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800876 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800877
Ruben Brunkcc776712015-02-17 20:18:47 -0800878 // Return error if the device was unplugged or removed by the HAL for some reason
879 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
880 return ret;
881 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800882
Ruben Brunkcc776712015-02-17 20:18:47 -0800883 // Get current active client PIDs
884 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
885 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800886
Ruben Brunkcc776712015-02-17 20:18:47 -0800887 std::vector<int> priorities(ownerPids.size(), PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800888
Ruben Brunkcc776712015-02-17 20:18:47 -0800889 // Get priorites of all active PIDs
890 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
891 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700892
Ruben Brunkcc776712015-02-17 20:18:47 -0800893 // Update all active clients' priorities
894 std::map<int,int> pidToPriorityMap;
895 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
896 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
897 }
898 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800899
Ruben Brunkcc776712015-02-17 20:18:47 -0800900 // Get state for the given cameraId
901 auto state = getCameraState(cameraId);
902 if (state == nullptr) {
903 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
904 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700905 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -0700906 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800907
908 // Make descriptor for incoming client
909 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
910 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
911 state->getConflicting(),
912 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
913
914 // Find clients that would be evicted
915 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
916
917 // If the incoming client was 'evicted,' higher priority clients have the camera in the
918 // background, so we cannot do evictions
919 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
920 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
921 " priority).", clientPid);
922
923 sp<BasicClient> clientSp = clientDescriptor->getValue();
924 String8 curTime = getFormattedCurrentTime();
925 auto incompatibleClients =
926 mActiveClientManager.getIncompatibleClients(clientDescriptor);
927
928 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
929 "(PID %d, priority %d)", curTime.string(),
930 cameraId.string(), packageName.string(), clientPid,
931 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
932
933 for (auto& i : incompatibleClients) {
934 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
935 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
936 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
937 i->getPriority());
938 }
939
940 // Log the client's attempt
941 mEventLog.add(msg);
942
943 return -EBUSY;
944 }
945
946 for (auto& i : evicted) {
947 sp<BasicClient> clientSp = i->getValue();
948 if (clientSp.get() == nullptr) {
949 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
950
951 // TODO: Remove this
952 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
953 __FUNCTION__);
954 mActiveClientManager.remove(i);
955 continue;
956 }
957
958 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
959 i->getKey().string());
960 evictedClients.push_back(clientSp);
961
962 String8 curTime = getFormattedCurrentTime();
963
964 // Log the clients evicted
965 mEventLog.add(String8::format("%s : EVICT device %s client for package %s (PID %"
966 PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for "
967 "package %s (PID %d, priority %" PRId32 ")", curTime.string(),
968 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
969 i->getOwnerId(), i->getPriority(), cameraId.string(),
970 packageName.string(), clientPid,
971 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
972
973 // Notify the client of disconnection
974 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
975 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -0700976 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700977 }
978
Ruben Brunkcc776712015-02-17 20:18:47 -0800979 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
980 // other clients from connecting in mServiceLockWrapper if held
981 mServiceLock.unlock();
982
983 // Clear caller identity temporarily so client disconnect PID checks work correctly
984 int64_t token = IPCThreadState::self()->clearCallingIdentity();
985
986 // Destroy evicted clients
987 for (auto& i : evictedClients) {
988 // Disconnect is blocking, and should only have returned when HAL has cleaned up
989 i->disconnect(); // Clients will remove themselves from the active client list here
990 }
991 evictedClients.clear();
992
993 IPCThreadState::self()->restoreCallingIdentity(token);
994
995 // Once clients have been disconnected, relock
996 mServiceLock.lock();
997
998 // Check again if the device was unplugged or something while we weren't holding mServiceLock
999 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1000 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001001 }
1002
Ruben Brunkcc776712015-02-17 20:18:47 -08001003 *partial = clientDescriptor;
1004 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001005}
1006
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001007status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001008 const sp<ICameraClient>& cameraClient,
1009 int cameraId,
1010 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001011 int clientUid,
1012 /*out*/
1013 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001014
Ruben Brunkcc776712015-02-17 20:18:47 -08001015 status_t ret = NO_ERROR;
1016 String8 id = String8::format("%d", cameraId);
1017 sp<Client> client = nullptr;
1018 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
1019 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001020
Ruben Brunkcc776712015-02-17 20:18:47 -08001021 if(ret != NO_ERROR) {
1022 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 }
1024
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001025 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001026 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027}
1028
Zhijun Heb10cdad2014-06-16 16:38:35 -07001029status_t CameraService::connectLegacy(
1030 const sp<ICameraClient>& cameraClient,
1031 int cameraId, int halVersion,
1032 const String16& clientPackageName,
1033 int clientUid,
1034 /*out*/
1035 sp<ICamera>& device) {
1036
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001037 int apiVersion = mModule->getRawModule()->module_api_version;
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001038 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001039 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001040 /*
1041 * Either the HAL version is unspecified in which case this just creates
1042 * a camera client selected by the latest device version, or
1043 * it's a particular version in which case the HAL must supported
1044 * the open_legacy call
1045 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001046 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001047 __FUNCTION__, apiVersion);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001048 return INVALID_OPERATION;
1049 }
1050
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 status_t ret = NO_ERROR;
1052 String8 id = String8::format("%d", cameraId);
1053 sp<Client> client = nullptr;
1054 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
1055 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001056
Ruben Brunkcc776712015-02-17 20:18:47 -08001057 if(ret != NO_ERROR) {
1058 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001059 }
1060
Zhijun Heb10cdad2014-06-16 16:38:35 -07001061 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001062 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001063}
1064
Ruben Brunkcc776712015-02-17 20:18:47 -08001065status_t CameraService::connectPro(const sp<IProCameraCallbacks>& cameraCb,
1066 int cameraId,
1067 const String16& clientPackageName,
1068 int clientUid,
1069 /*out*/
1070 sp<IProCameraUser>& device) {
1071 ALOGE("%s: Unimplemented, please use connectDevice", __FUNCTION__);
1072 return INVALID_OPERATION;
1073}
1074
1075status_t CameraService::connectDevice(
1076 const sp<ICameraDeviceCallbacks>& cameraCb,
1077 int cameraId,
1078 const String16& clientPackageName,
1079 int clientUid,
1080 /*out*/
1081 sp<ICameraDeviceUser>& device) {
1082
1083 status_t ret = NO_ERROR;
1084 String8 id = String8::format("%d", cameraId);
1085 sp<CameraDeviceClient> client = nullptr;
1086 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1087 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
1088 /*out*/client);
1089
1090 if(ret != NO_ERROR) {
1091 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001092 }
1093
Ruben Brunkcc776712015-02-17 20:18:47 -08001094 device = client;
1095 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001096}
1097
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001098status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1099 const sp<IBinder>& clientBinder) {
1100 if (enabled && clientBinder == NULL) {
1101 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001102 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001103 }
1104
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001105 String8 id = String8(cameraId.string());
1106
1107 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001108 auto state = getCameraState(id);
1109 if (state == nullptr) {
1110 ALOGE("%s: camera id is invalid %s", id.string());
1111 return -EINVAL;
1112 }
1113
1114 ICameraServiceListener::Status cameraStatus = state->getStatus();
1115 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1116 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001117 ALOGE("%s: camera id is invalid %s", id.string());
1118 return -EINVAL;
1119 }
1120
1121 {
1122 Mutex::Autolock al(mTorchStatusMutex);
1123 ICameraServiceListener::TorchStatus status;
1124 status_t res = getTorchStatusLocked(id, &status);
1125 if (res) {
1126 ALOGE("%s: getting current torch status failed for camera %s",
1127 __FUNCTION__, id.string());
1128 return -EINVAL;
1129 }
1130
1131 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001133 ALOGE("%s: torch mode of camera %s is not available because "
1134 "camera is in use", __FUNCTION__, id.string());
1135 return -EBUSY;
1136 } else {
1137 ALOGE("%s: torch mode of camera %s is not available due to "
1138 "insufficient resources", __FUNCTION__, id.string());
1139 return -EUSERS;
1140 }
1141 }
1142 }
1143
1144 status_t res = mFlashlight->setTorchMode(id, enabled);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001145 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001146 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1147 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001148 return res;
1149 }
1150
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001151 {
1152 // update the link to client's death
1153 Mutex::Autolock al(mTorchClientMapMutex);
1154 ssize_t index = mTorchClientMap.indexOfKey(id);
1155 if (enabled) {
1156 if (index == NAME_NOT_FOUND) {
1157 mTorchClientMap.add(id, clientBinder);
1158 } else {
1159 const sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
1160 oldBinder->unlinkToDeath(this);
1161
1162 mTorchClientMap.replaceValueAt(index, clientBinder);
1163 }
1164 clientBinder->linkToDeath(this);
1165 } else if (index != NAME_NOT_FOUND) {
1166 sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001167 oldBinder->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001168 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001169 }
1170
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001171 return OK;
1172}
1173
Igor Murashkinbfc99152013-02-27 12:55:20 -08001174status_t CameraService::addListener(
1175 const sp<ICameraServiceListener>& listener) {
1176 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001177
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001178 if (listener == 0) {
1179 ALOGE("%s: Listener must not be null", __FUNCTION__);
1180 return BAD_VALUE;
1181 }
1182
Igor Murashkinbfc99152013-02-27 12:55:20 -08001183 Mutex::Autolock lock(mServiceLock);
1184
Ruben Brunkcc776712015-02-17 20:18:47 -08001185 {
1186 Mutex::Autolock lock(mStatusListenerLock);
1187 for (auto& it : mListenerList) {
1188 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1189 ALOGW("%s: Tried to add listener %p which was already subscribed",
1190 __FUNCTION__, listener.get());
1191 return ALREADY_EXISTS;
1192 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001193 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001194
1195 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001196 }
1197
Igor Murashkinbfc99152013-02-27 12:55:20 -08001198
Igor Murashkincba2c162013-03-20 15:56:31 -07001199 /* Immediately signal current status to this listener only */
1200 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001201 Mutex::Autolock lock(mCameraStatesLock);
1202 for (auto& i : mCameraStates) {
1203 // TODO: Update binder to use String16 for camera IDs and remove;
1204 int id = cameraIdToInt(i.first);
1205 if (id == -1) continue;
1206
1207 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001208 }
1209 }
1210
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001211 /* Immediately signal current torch status to this listener only */
1212 {
1213 Mutex::Autolock al(mTorchStatusMutex);
1214 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001215 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1216 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001217 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001218 }
1219
Igor Murashkinbfc99152013-02-27 12:55:20 -08001220 return OK;
1221}
Ruben Brunkcc776712015-02-17 20:18:47 -08001222
1223status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001224 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1225
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001226 if (listener == 0) {
1227 ALOGE("%s: Listener must not be null", __FUNCTION__);
1228 return BAD_VALUE;
1229 }
1230
Igor Murashkinbfc99152013-02-27 12:55:20 -08001231 Mutex::Autolock lock(mServiceLock);
1232
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 {
1234 Mutex::Autolock lock(mStatusListenerLock);
1235 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1236 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1237 mListenerList.erase(it);
1238 return OK;
1239 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001240 }
1241 }
1242
1243 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1244 __FUNCTION__, listener.get());
1245
1246 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001247}
1248
Ruben Brunkcc776712015-02-17 20:18:47 -08001249status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001250 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1251
1252 if (parameters == NULL) {
1253 ALOGE("%s: parameters must not be null", __FUNCTION__);
1254 return BAD_VALUE;
1255 }
1256
1257 status_t ret = 0;
1258
1259 CameraParameters shimParams;
1260 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1261 // Error logged by caller
1262 return ret;
1263 }
1264
1265 String8 shimParamsString8 = shimParams.flatten();
1266 String16 shimParamsString16 = String16(shimParamsString8);
1267
1268 *parameters = shimParamsString16;
1269
1270 return OK;
1271}
1272
1273status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1274 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1275
1276 switch (apiVersion) {
1277 case API_VERSION_1:
1278 case API_VERSION_2:
1279 break;
1280 default:
1281 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1282 return BAD_VALUE;
1283 }
1284
1285 int facing = -1;
1286 int deviceVersion = getDeviceVersion(cameraId, &facing);
1287
1288 switch(deviceVersion) {
1289 case CAMERA_DEVICE_API_VERSION_1_0:
1290 case CAMERA_DEVICE_API_VERSION_2_0:
1291 case CAMERA_DEVICE_API_VERSION_2_1:
1292 case CAMERA_DEVICE_API_VERSION_3_0:
1293 case CAMERA_DEVICE_API_VERSION_3_1:
1294 if (apiVersion == API_VERSION_2) {
1295 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1296 __FUNCTION__, cameraId);
1297 return -EOPNOTSUPP;
1298 } else { // if (apiVersion == API_VERSION_1) {
1299 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1300 __FUNCTION__, cameraId);
1301 return OK;
1302 }
1303 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001304 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001305 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1306 __FUNCTION__, cameraId);
1307 return OK;
1308 case -1:
1309 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1310 return BAD_VALUE;
1311 default:
1312 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1313 return INVALID_OPERATION;
1314 }
1315
1316 return OK;
1317}
1318
Ruben Brunkcc776712015-02-17 20:18:47 -08001319void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001320 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001321 for (auto& i : mActiveClientManager.getAll()) {
1322 auto clientSp = i->getValue();
1323 if (clientSp.get() == client) {
1324 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001325 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001326 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001327}
1328
Ruben Brunkcc776712015-02-17 20:18:47 -08001329bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1330 const int callingPid = getCallingPid();
1331 const int servicePid = getpid();
1332 bool ret = false;
1333 {
1334 // Acquire mServiceLock and prevent other clients from connecting
1335 std::unique_ptr<AutoConditionLock> lock =
1336 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001337
Igor Murashkin634a5152013-02-20 17:15:11 -08001338
Ruben Brunkcc776712015-02-17 20:18:47 -08001339 std::vector<sp<BasicClient>> evicted;
1340 for (auto& i : mActiveClientManager.getAll()) {
1341 auto clientSp = i->getValue();
1342 if (clientSp.get() == nullptr) {
1343 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1344 mActiveClientManager.remove(i);
1345 continue;
1346 }
1347 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1348 callingPid == clientSp->getClientPid())) {
1349 mActiveClientManager.remove(i);
1350 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001351
Ruben Brunkcc776712015-02-17 20:18:47 -08001352 // Notify the client of disconnection
1353 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1354 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001355 }
1356 }
1357
Ruben Brunkcc776712015-02-17 20:18:47 -08001358 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1359 // other clients from connecting in mServiceLockWrapper if held
1360 mServiceLock.unlock();
1361
1362 for (auto& i : evicted) {
1363 if (i.get() != nullptr) {
1364 i->disconnect();
1365 ret = true;
1366 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001367 }
1368
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 // Reacquire mServiceLock
1370 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001371
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 } // lock is destroyed, allow further connect calls
1373
1374 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001375}
1376
Igor Murashkinecf17e82012-10-02 16:05:11 -07001377
Ruben Brunkcc776712015-02-17 20:18:47 -08001378std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1379 const String8& cameraId) const {
1380 std::shared_ptr<CameraState> state;
1381 {
1382 Mutex::Autolock lock(mCameraStatesLock);
1383 auto iter = mCameraStates.find(cameraId);
1384 if (iter != mCameraStates.end()) {
1385 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 }
1387 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389}
1390
Ruben Brunkcc776712015-02-17 20:18:47 -08001391sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1392 // Remove from active clients list
1393 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1394 if (clientDescriptorPtr == nullptr) {
1395 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1396 cameraId.string());
1397 return sp<BasicClient>{nullptr};
1398 }
1399
1400 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001401}
1402
Ruben Brunkcc776712015-02-17 20:18:47 -08001403
1404void CameraService::logDisconnected(const String8& cameraId, int clientPid,
1405 const String8& clientPackage) {
1406
1407 String8 curTime = getFormattedCurrentTime();
1408 // Log the clients evicted
1409 mEventLog.add(String8::format("%s : DISCONNECT device %s client for package %s (PID %d)",
1410 curTime.string(), cameraId.string(), clientPackage.string(), clientPid));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411}
1412
Ruben Brunkcc776712015-02-17 20:18:47 -08001413void CameraService::logConnected(const String8& cameraId, int clientPid,
1414 const String8& clientPackage) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001415
Ruben Brunkcc776712015-02-17 20:18:47 -08001416 String8 curTime = getFormattedCurrentTime();
1417 // Log the clients evicted
1418 mEventLog.add(String8::format("%s : CONNECT device %s client for package %s (PID %d)",
1419 curTime.string(), cameraId.string(), clientPackage.string(), clientPid));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001420}
1421
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422status_t CameraService::onTransact(
1423 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
1424 // Permission checks
1425 switch (code) {
1426 case BnCameraService::CONNECT:
Igor Murashkin634a5152013-02-20 17:15:11 -08001427 case BnCameraService::CONNECT_PRO:
Eino-Ville Talvala63d877f2014-06-16 19:21:12 -07001428 case BnCameraService::CONNECT_DEVICE:
Zhijun Heb10cdad2014-06-16 16:38:35 -07001429 case BnCameraService::CONNECT_LEGACY:
Mathias Agopian65ab4712010-07-14 17:59:35 -07001430 const int pid = getCallingPid();
1431 const int self_pid = getpid();
1432 if (pid != self_pid) {
1433 // we're called from a different process, do the real check
1434 if (!checkCallingPermission(
1435 String16("android.permission.CAMERA"))) {
1436 const int uid = getCallingUid();
Steve Block29357bc2012-01-06 19:20:56 +00001437 ALOGE("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438 "can't use the camera pid=%d, uid=%d", pid, uid);
1439 return PERMISSION_DENIED;
1440 }
1441 }
1442 break;
1443 }
1444
1445 return BnCameraService::onTransact(code, data, reply, flags);
1446}
1447
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448// We share the media players for shutter and recording sound for all clients.
1449// A reference count is kept to determine when we will actually release the
1450// media players.
1451
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001452MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001454 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001455 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 mp->prepare();
1457 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001458 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459 return NULL;
1460 }
1461 return mp;
1462}
1463
1464void CameraService::loadSound() {
1465 Mutex::Autolock lock(mSoundLock);
1466 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1467 if (mSoundRef++) return;
1468
1469 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1470 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1471}
1472
1473void CameraService::releaseSound() {
1474 Mutex::Autolock lock(mSoundLock);
1475 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1476 if (--mSoundRef) return;
1477
1478 for (int i = 0; i < NUM_SOUNDS; i++) {
1479 if (mSoundPlayer[i] != 0) {
1480 mSoundPlayer[i]->disconnect();
1481 mSoundPlayer[i].clear();
1482 }
1483 }
1484}
1485
1486void CameraService::playSound(sound_kind kind) {
1487 LOG1("playSound(%d)", kind);
1488 Mutex::Autolock lock(mSoundLock);
1489 sp<MediaPlayer> player = mSoundPlayer[kind];
1490 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001491 player->seekTo(0);
1492 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 }
1494}
1495
1496// ----------------------------------------------------------------------------
1497
1498CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001499 const sp<ICameraClient>& cameraClient,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001500 const String16& clientPackageName,
1501 int cameraId, int cameraFacing,
1502 int clientPid, uid_t clientUid,
1503 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001504 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001505 IInterface::asBinder(cameraClient),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001506 clientPackageName,
1507 cameraId, cameraFacing,
1508 clientPid, clientUid,
1509 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001510{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001512 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001514 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001517
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001518 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519}
1520
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521// tear down the client
1522CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001523 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001524 mDestructionStarted = true;
1525
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001526 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001527 // unconditionally disconnect. function is idempotent
1528 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529}
1530
Igor Murashkin634a5152013-02-20 17:15:11 -08001531CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001532 const sp<IBinder>& remoteCallback,
1533 const String16& clientPackageName,
1534 int cameraId, int cameraFacing,
1535 int clientPid, uid_t clientUid,
1536 int servicePid):
Ruben Brunkcc776712015-02-17 20:18:47 -08001537 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001538{
1539 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001540 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001541 mCameraId = cameraId;
1542 mCameraFacing = cameraFacing;
1543 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001544 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001545 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001546 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001547 mDestructionStarted = false;
1548}
1549
1550CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001551 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001552 mDestructionStarted = true;
1553}
1554
1555void CameraService::BasicClient::disconnect() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001556 if (mDisconnected) return;
1557 mDisconnected = true;;
1558
1559 mCameraService->removeByClient(this);
1560 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
1561 String8(mClientPackageName));
1562
1563 sp<IBinder> remote = getRemote();
1564 if (remote != nullptr) {
1565 remote->unlinkToDeath(mCameraService);
1566 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001567
1568 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001569 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1570
Igor Murashkincba2c162013-03-20 15:56:31 -07001571 // client shouldn't be able to call into us anymore
1572 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001573}
1574
Ruben Brunkcc776712015-02-17 20:18:47 -08001575String16 CameraService::BasicClient::getPackageName() const {
1576 return mClientPackageName;
1577}
1578
1579
1580int CameraService::BasicClient::getClientPid() const {
1581 return mClientPid;
1582}
1583
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001584status_t CameraService::BasicClient::startCameraOps() {
1585 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001586 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001587 mOpsCallback = new OpsCallback(this);
1588
Igor Murashkine6800ce2013-03-04 17:25:57 -08001589 {
1590 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1591 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1592 }
1593
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001594 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1595 mClientPackageName, mOpsCallback);
1596 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1597 mClientUid, mClientPackageName);
1598
1599 if (res != AppOpsManager::MODE_ALLOWED) {
1600 ALOGI("Camera %d: Access for \"%s\" has been revoked",
1601 mCameraId, String8(mClientPackageName).string());
1602 return PERMISSION_DENIED;
1603 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001604
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001605 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001606
1607 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1608 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001609 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001610
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001611 return OK;
1612}
1613
1614status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001615 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001616 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001617 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001618 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1619 mClientPackageName);
1620 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001621
Ruben Brunkcc776712015-02-17 20:18:47 -08001622 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1623 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001624
Ruben Brunkcc776712015-02-17 20:18:47 -08001625 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001626 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001627 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001628
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001629 // Notify flashlight that a camera device is closed.
1630 mCameraService->mFlashlight->deviceClosed(
1631 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001632 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001633 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001634 if (mOpsCallback != NULL) {
1635 mAppOpsManager.stopWatchingMode(mOpsCallback);
1636 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001637 mOpsCallback.clear();
1638
1639 return OK;
1640}
1641
1642void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1643 String8 name(packageName);
1644 String8 myName(mClientPackageName);
1645
1646 if (op != AppOpsManager::OP_CAMERA) {
1647 ALOGW("Unexpected app ops notification received: %d", op);
1648 return;
1649 }
1650
1651 int32_t res;
1652 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1653 mClientUid, mClientPackageName);
1654 ALOGV("checkOp returns: %d, %s ", res,
1655 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1656 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1657 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1658 "UNKNOWN");
1659
1660 if (res != AppOpsManager::MODE_ALLOWED) {
1661 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1662 myName.string());
1663 // Reset the client PID to allow server-initiated disconnect,
1664 // and to prevent further calls by client.
1665 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07001666 CaptureResultExtras resultExtras; // a dummy result (invalid)
1667 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001668 disconnect();
1669 }
1670}
1671
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672// ----------------------------------------------------------------------------
1673
Ruben Brunkcc776712015-02-17 20:18:47 -08001674// Provide client strong pointer for callbacks.
1675sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
1676 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
1677 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
1678 if (clientDescriptor != nullptr) {
1679 return sp<Client>{
1680 static_cast<Client*>(clientDescriptor->getValue().get())};
1681 }
1682 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683}
1684
Jianing Weicb0652e2014-03-12 18:29:36 -07001685void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1686 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001687 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001688}
1689
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001690// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07001691void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001692 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08001693 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08001694}
1695
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001696CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1697 mClient(client) {
1698}
1699
1700void CameraService::Client::OpsCallback::opChanged(int32_t op,
1701 const String16& packageName) {
1702 sp<BasicClient> client = mClient.promote();
1703 if (client != NULL) {
1704 client->opChanged(op, packageName);
1705 }
1706}
1707
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708// ----------------------------------------------------------------------------
Igor Murashkin634a5152013-02-20 17:15:11 -08001709// IProCamera
1710// ----------------------------------------------------------------------------
1711
1712CameraService::ProClient::ProClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001713 const sp<IProCameraCallbacks>& remoteCallback,
1714 const String16& clientPackageName,
1715 int cameraId,
1716 int cameraFacing,
1717 int clientPid,
1718 uid_t clientUid,
1719 int servicePid)
Marco Nelissenf8880202014-11-14 07:58:25 -08001720 : CameraService::BasicClient(cameraService, IInterface::asBinder(remoteCallback),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001721 clientPackageName, cameraId, cameraFacing,
1722 clientPid, clientUid, servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001723{
1724 mRemoteCallback = remoteCallback;
1725}
1726
1727CameraService::ProClient::~ProClient() {
Igor Murashkin634a5152013-02-20 17:15:11 -08001728}
1729
Jianing Weicb0652e2014-03-12 18:29:36 -07001730void CameraService::ProClient::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1731 const CaptureResultExtras& resultExtras) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001732 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001733}
1734
Igor Murashkin634a5152013-02-20 17:15:11 -08001735// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08001736// CameraState
1737// ----------------------------------------------------------------------------
1738
1739CameraService::CameraState::CameraState(const String8& id, int cost,
1740 const std::set<String8>& conflicting) : mId(id),
1741 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
1742
1743CameraService::CameraState::~CameraState() {}
1744
1745ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
1746 Mutex::Autolock lock(mStatusLock);
1747 return mStatus;
1748}
1749
1750CameraParameters CameraService::CameraState::getShimParams() const {
1751 return mShimParams;
1752}
1753
1754void CameraService::CameraState::setShimParams(const CameraParameters& params) {
1755 mShimParams = params;
1756}
1757
1758int CameraService::CameraState::getCost() const {
1759 return mCost;
1760}
1761
1762std::set<String8> CameraService::CameraState::getConflicting() const {
1763 return mConflicting;
1764}
1765
1766String8 CameraService::CameraState::getId() const {
1767 return mId;
1768}
1769
1770// ----------------------------------------------------------------------------
1771// CameraClientManager
1772// ----------------------------------------------------------------------------
1773
1774CameraService::CameraClientManager::~CameraClientManager() {}
1775
1776sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
1777 const String8& id) const {
1778 auto descriptor = get(id);
1779 if (descriptor == nullptr) {
1780 return sp<BasicClient>{nullptr};
1781 }
1782 return descriptor->getValue();
1783}
1784
1785String8 CameraService::CameraClientManager::toString() const {
1786 auto all = getAll();
1787 String8 ret("[");
1788 bool hasAny = false;
1789 for (auto& i : all) {
1790 hasAny = true;
1791 String8 key = i->getKey();
1792 int32_t cost = i->getCost();
1793 int32_t pid = i->getOwnerId();
1794 int32_t priority = i->getPriority();
1795 auto conflicting = i->getConflicting();
1796 auto clientSp = i->getValue();
1797 String8 packageName;
1798 if (clientSp.get() != nullptr) {
1799 packageName = String8{clientSp->getPackageName()};
1800 }
1801 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
1802 PRId32 ", ", key.string(), cost, pid, priority);
1803
1804 if (packageName.size() != 0) {
1805 ret.appendFormat("Client Package Name: %s", packageName.string());
1806 }
1807
1808 ret.append(", Conflicting Client Devices: {");
1809 for (auto& j : conflicting) {
1810 ret.appendFormat("%s, ", j.string());
1811 }
1812 ret.append("})");
1813 }
1814 if (hasAny) ret.append("\n");
1815 ret.append("]\n");
1816 return ret;
1817}
1818
1819CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1820 const String8& key, const sp<BasicClient>& value, int32_t cost,
1821 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
1822
1823 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
1824 key, value, cost, conflictingKeys, priority, ownerId);
1825}
1826
1827CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
1828 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
1829 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
1830 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
1831}
1832
1833// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834
1835static const int kDumpLockRetries = 50;
1836static const int kDumpLockSleep = 60000;
1837
1838static bool tryLock(Mutex& mutex)
1839{
1840 bool locked = false;
1841 for (int i = 0; i < kDumpLockRetries; ++i) {
1842 if (mutex.tryLock() == NO_ERROR) {
1843 locked = true;
1844 break;
1845 }
1846 usleep(kDumpLockSleep);
1847 }
1848 return locked;
1849}
1850
1851status_t CameraService::dump(int fd, const Vector<String16>& args) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 String8 result;
1853 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07001854 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 "can't dump CameraService from pid=%d, uid=%d\n",
1856 getCallingPid(),
1857 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 write(fd, result.string(), result.size());
1859 } else {
1860 bool locked = tryLock(mServiceLock);
1861 // failed to lock - CameraService is probably deadlocked
1862 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07001863 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001864 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 }
1866
1867 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001868 if (!mModule) {
1869 result = String8::format("No camera module available!\n");
1870 write(fd, result.string(), result.size());
Kalle Lampila6ec3a152013-04-30 15:27:19 +03001871 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001872 return NO_ERROR;
1873 }
1874
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001875 const hw_module_t* common = mModule->getRawModule();
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 result = String8::format("Camera module HAL API version: %#x\n", common->hal_api_version);
1877 result.appendFormat("Camera module API version: %#x\n", common->module_api_version);
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001878 result.appendFormat("Camera module name: %s\n", common->name);
1879 result.appendFormat("Camera module author: %s\n", common->author);
Ruben Brunkcc776712015-02-17 20:18:47 -08001880 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
1881 String8 activeClientString = mActiveClientManager.toString();
1882 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
1883
Ruben Brunkf81648e2014-04-17 16:14:57 -07001884
1885 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1886 if (desc == NULL) {
1887 result.appendFormat("Vendor tags left unimplemented.\n");
1888 } else {
1889 result.appendFormat("Vendor tag definitions:\n");
1890 }
1891
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001892 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07001893
1894 if (desc != NULL) {
1895 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
1896 }
1897
Ruben Brunkcc776712015-02-17 20:18:47 -08001898 result = String8("Prior client events (most recent at top):\n");
1899
1900 for (const auto& msg : mEventLog) {
1901 result.appendFormat("%s\n", msg.string());
1902 }
1903
1904 if (mEventLog.size() == DEFAULT_EVICTION_LOG_LENGTH) {
1905 result.append("...\n");
1906 }
1907
1908 write(fd, result.string(), result.size());
1909
1910 bool stateLocked = tryLock(mCameraStatesLock);
1911 if (!stateLocked) {
1912 result = String8::format("CameraStates in use, may be deadlocked\n");
1913 write(fd, result.string(), result.size());
1914 }
1915
1916 for (auto& state : mCameraStates) {
1917 String8 cameraId = state.first;
1918 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001919 camera_info info;
1920
Ruben Brunkcc776712015-02-17 20:18:47 -08001921 // TODO: Change getCameraInfo + HAL to use String cameraIds
1922 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001923 if (rc != OK) {
1924 result.appendFormat(" Error reading static information!\n");
1925 write(fd, result.string(), result.size());
1926 } else {
1927 result.appendFormat(" Facing: %s\n",
1928 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
1929 result.appendFormat(" Orientation: %d\n", info.orientation);
1930 int deviceVersion;
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001931 if (common->module_api_version < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001932 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
1933 } else {
1934 deviceVersion = info.device_version;
1935 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001936
1937 auto conflicting = state.second->getConflicting();
1938 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
1939 result.appendFormat(" Conflicting Devices:");
1940 for (auto& id : conflicting) {
1941 result.appendFormat(" %s", cameraId.string());
1942 }
1943 if (conflicting.size() == 0) {
1944 result.appendFormat(" NONE");
1945 }
1946 result.appendFormat("\n");
1947
1948 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001949 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
1950 result.appendFormat(" Device static metadata:\n");
1951 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07001952 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07001953 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001954 } else {
1955 write(fd, result.string(), result.size());
1956 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001957
1958 CameraParameters p = state.second->getShimParams();
1959 if (!p.isEmpty()) {
1960 result = String8::format(" Camera1 API shim is using parameters:\n ");
1961 write(fd, result.string(), result.size());
1962 p.dump(fd, args);
1963 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001964 }
1965
Ruben Brunkcc776712015-02-17 20:18:47 -08001966 auto clientDescriptor = mActiveClientManager.get(cameraId);
1967 if (clientDescriptor == nullptr) {
1968 result = String8::format(" Device %s is closed, no client instance\n",
1969 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001970 write(fd, result.string(), result.size());
1971 continue;
1972 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001974 result = String8::format(" Device %s is open. Client instance dump:\n\n",
1975 cameraId.string());
1976 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
1977 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
1978
1979 auto client = clientDescriptor->getValue();
1980 result.appendFormat("Client package: %s\n",
1981 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001982 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08001983
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07001984 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001986
1987 if (stateLocked) mCameraStatesLock.unlock();
1988
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07001990 result = String8::format("\nNo active camera clients yet.\n");
1991 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 }
1993
1994 if (locked) mServiceLock.unlock();
1995
Igor Murashkinff3e31d2013-10-23 16:40:06 -07001996 // Dump camera traces if there were any
1997 write(fd, "\n", 1);
1998 camera3::CameraTraces::dump(fd, args);
1999
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 // change logging level
2001 int n = args.size();
2002 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002003 String16 verboseOption("-v");
2004 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 String8 levelStr(args[i+1]);
2006 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002007 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002009 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 }
2011 }
2012 }
2013 return NO_ERROR;
2014}
2015
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002016void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002017 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002018 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2019 if (mTorchClientMap[i] == who) {
2020 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002021 String8 cameraId = mTorchClientMap.keyAt(i);
2022 status_t res = mFlashlight->setTorchMode(cameraId, false);
2023 if (res) {
2024 ALOGE("%s: torch client died but couldn't turn off torch: "
2025 "%s (%d)", __FUNCTION__, strerror(-res), res);
2026 return;
2027 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002028 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002029 break;
2030 }
2031 }
2032}
2033
Ruben Brunkcc776712015-02-17 20:18:47 -08002034/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002035
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002036 /**
2037 * While tempting to promote the wp<IBinder> into a sp,
2038 * it's actually not supported by the binder driver
2039 */
2040
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002041 // check torch client
2042 handleTorchClientBinderDied(who);
2043
2044 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002045 if(!evictClientIdByRemote(who)) {
2046 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002047 return;
2048 }
2049
Ruben Brunkcc776712015-02-17 20:18:47 -08002050 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2051 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002052}
2053
Ruben Brunkcc776712015-02-17 20:18:47 -08002054void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2055 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002056}
2057
Ruben Brunkcc776712015-02-17 20:18:47 -08002058void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2059 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2060 // Do not lock mServiceLock here or can get into a deadlock from
2061 // connect() -> disconnect -> updateStatus
2062
2063 auto state = getCameraState(cameraId);
2064
2065 if (state == nullptr) {
2066 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2067 cameraId.string());
2068 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002069 }
2070
Ruben Brunkcc776712015-02-17 20:18:47 -08002071 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2072 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2073 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2074 (const String8& cameraId, ICameraServiceListener::Status status) {
2075
2076 // Update torch status
2077 if (status == ICameraServiceListener::STATUS_NOT_PRESENT ||
2078 status == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
2079 // Update torch status to not available when the camera device becomes not present
2080 // or not available.
2081 onTorchStatusChanged(cameraId, ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE);
2082 } else if (status == ICameraServiceListener::STATUS_PRESENT) {
2083 // Update torch status to available when the camera device becomes present or
2084 // available
2085 onTorchStatusChanged(cameraId, ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
2086 }
2087
2088 Mutex::Autolock lock(mStatusListenerLock);
2089
2090 for (auto& listener : mListenerList) {
2091 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2092 int id = cameraIdToInt(cameraId);
2093 if (id != -1) listener->onStatusChanged(status, id);
2094 }
2095 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002096}
2097
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002098status_t CameraService::getTorchStatusLocked(
2099 const String8& cameraId,
2100 ICameraServiceListener::TorchStatus *status) const {
2101 if (!status) {
2102 return BAD_VALUE;
2103 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002104 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2105 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002106 // invalid camera ID or the camera doesn't have a flash unit
2107 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002108 }
2109
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002110 *status = mTorchStatusMap.valueAt(index);
2111 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002112}
2113
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002114status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002115 ICameraServiceListener::TorchStatus status) {
2116 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2117 if (index == NAME_NOT_FOUND) {
2118 return BAD_VALUE;
2119 }
2120 ICameraServiceListener::TorchStatus& item =
2121 mTorchStatusMap.editValueAt(index);
2122 item = status;
2123
2124 return OK;
2125}
2126
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127}; // namespace android