blob: 0e2969ae057df77336b26b5ffec0e5a4b7bd9b5c [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"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080031#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryBase.h>
35#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080036#include <binder/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070038#include <cutils/properties.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>
Ruben Brunk99e69712015-05-26 17:25:07 -070044#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/Errors.h>
46#include <utils/Log.h>
47#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080048#include <utils/Trace.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080049#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080050#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070051#include <system/camera_metadata.h>
52#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070055#include "api1/CameraClient.h"
56#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070058#include "utils/CameraTraces.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080060namespace {
61 const char* kPermissionServiceName = "permission";
62}; // namespace anonymous
63
Mathias Agopian65ab4712010-07-14 17:59:35 -070064namespace android {
65
66// ----------------------------------------------------------------------------
67// Logging support -- this is for debugging only
68// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070069volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
Steve Blockb8a80522011-12-20 16:23:08 +000071#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
72#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070073
74static void setLogLevel(int level) {
75 android_atomic_write(level, &gLogLevel);
76}
77
78// ----------------------------------------------------------------------------
79
Igor Murashkincba2c162013-03-20 15:56:31 -070080extern "C" {
81static void camera_device_status_change(
82 const struct camera_module_callbacks* callbacks,
83 int camera_id,
84 int new_status) {
85 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080086 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070087
Bin Chene16d1162016-02-22 18:19:58 +110088 cs->onDeviceStatusChanged(camera_id,
Ruben Brunkcc776712015-02-17 20:18:47 -080089 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070090}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080091
92static void torch_mode_status_change(
93 const struct camera_module_callbacks* callbacks,
94 const char* camera_id,
95 int new_status) {
96 if (!callbacks || !camera_id) {
97 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
98 callbacks, camera_id);
99 }
100 sp<CameraService> cs = const_cast<CameraService*>(
101 static_cast<const CameraService*>(callbacks));
102
103 ICameraServiceListener::TorchStatus status;
104 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800105 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800106 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
107 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800108 case TORCH_MODE_STATUS_AVAILABLE_OFF:
109 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
110 break;
111 case TORCH_MODE_STATUS_AVAILABLE_ON:
112 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800113 break;
114 default:
115 ALOGE("Unknown torch status %d", new_status);
116 return;
117 }
118
119 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800120 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800121 status);
122}
Igor Murashkincba2c162013-03-20 15:56:31 -0700123} // extern "C"
124
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125// ----------------------------------------------------------------------------
126
127// This is ugly and only safe if we never re-create the CameraService, but
128// should be ok for now.
129static CameraService *gCameraService;
130
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800131CameraService::CameraService() :
132 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
133 mSoundRef(0), mModule(nullptr),
134 mNumberOfCameras(0), mNumberOfNormalCameras(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000135 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800137
Igor Murashkincba2c162013-03-20 15:56:31 -0700138 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800139 this->torch_mode_status_change = android::torch_mode_status_change;
140
Ruben Brunkcc776712015-02-17 20:18:47 -0800141 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700142}
143
Iliyan Malchev8951a972011-04-14 16:55:59 -0700144void CameraService::onFirstRef()
145{
Ruben Brunkcc776712015-02-17 20:18:47 -0800146 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800147
Iliyan Malchev8951a972011-04-14 16:55:59 -0700148 BnCameraService::onFirstRef();
149
Ruben Brunk99e69712015-05-26 17:25:07 -0700150 // Update battery life tracking if service is restarting
151 BatteryNotifier& notifier(BatteryNotifier::getInstance());
152 notifier.noteResetCamera();
153 notifier.noteResetFlashlight();
154
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800155 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700156 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
157 (const hw_module_t **)&rawModule);
158 if (err < 0) {
159 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
160 logServiceError("Could not load camera HAL module", err);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700161 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700162 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800163
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700164 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700165 err = mModule->init();
166 if (err != OK) {
167 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
168 strerror(-err));
169 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800170
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700171 delete mModule;
172 mModule = nullptr;
173 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700174 }
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700175 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700176
177 mNumberOfCameras = mModule->getNumberOfCameras();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700178 mNumberOfNormalCameras = mNumberOfCameras;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700179
Yin-Chia Yehd4a653a2015-10-14 11:05:44 -0700180 // Setup vendor tags before we call get_camera_info the first time
181 // because HAL might need to setup static vendor keys in get_camera_info
182 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
183 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
184 setUpVendorTags();
185 }
186
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700187 mFlashlight = new CameraFlashlight(*mModule, *this);
188 status_t res = mFlashlight->findFlashUnits();
189 if (res) {
190 // impossible because we haven't open any camera devices.
191 ALOGE("Failed to find flash units.");
192 }
193
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700194 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700195 for (int i = 0; i < mNumberOfCameras; i++) {
196 String8 cameraId = String8::format("%d", i);
197
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700198 // Get camera info
199
200 struct camera_info info;
201 bool haveInfo = true;
202 status_t rc = mModule->getCameraInfo(i, &info);
203 if (rc != NO_ERROR) {
204 ALOGE("%s: Received error loading camera info for device %d, cost and"
205 " conflicting devices fields set to defaults for this device.",
206 __FUNCTION__, i);
207 haveInfo = false;
208 }
209
210 // Check for backwards-compatibility support
211 if (haveInfo) {
212 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
213 delete mModule;
214 mModule = nullptr;
215 return;
216 }
217 }
218
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700219 // Defaults to use for cost and conflicting devices
220 int cost = 100;
221 char** conflicting_devices = nullptr;
222 size_t conflicting_devices_length = 0;
223
224 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700225 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
226 cost = info.resource_cost;
227 conflicting_devices = info.conflicting_devices;
228 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700229 }
230
231 std::set<String8> conflicting;
232 for (size_t i = 0; i < conflicting_devices_length; i++) {
233 conflicting.emplace(String8(conflicting_devices[i]));
234 }
235
236 // Initialize state for each camera device
237 {
238 Mutex::Autolock lock(mCameraStatesLock);
239 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
240 conflicting));
241 }
242
243 if (mFlashlight->hasFlashUnit(cameraId)) {
244 mTorchStatusMap.add(cameraId,
245 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
246 }
247 }
248
249 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
250 mModule->setCallbacks(this);
251 }
252
Ruben Brunk2823ce02015-05-19 17:25:13 -0700253 CameraService::pingCameraServiceProxy();
254}
255
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700256sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800257 sp<ICameraServiceProxy> proxyBinder = nullptr;
258#ifndef __BRILLO__
Ruben Brunk2823ce02015-05-19 17:25:13 -0700259 sp<IServiceManager> sm = defaultServiceManager();
260 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800261 if (binder != nullptr) {
262 proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700263 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800264#endif
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700265 return proxyBinder;
266}
267
268void CameraService::pingCameraServiceProxy() {
269 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
270 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700271 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700272}
273
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800275 if (mModule) {
276 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800277 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800278 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800279 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800280 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281}
282
Bin Chene16d1162016-02-22 18:19:58 +1100283void CameraService::onDeviceStatusChanged(int cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800284 camera_device_status_t newStatus) {
285 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700286 cameraId, newStatus);
287
Ruben Brunkcc776712015-02-17 20:18:47 -0800288 String8 id = String8::format("%d", cameraId);
289 std::shared_ptr<CameraState> state = getCameraState(id);
290
291 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700292 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
293 return;
294 }
295
Ruben Brunkcc776712015-02-17 20:18:47 -0800296 ICameraServiceListener::Status oldStatus = state->getStatus();
297
298 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
299 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700300 return;
301 }
302
Igor Murashkincba2c162013-03-20 15:56:31 -0700303 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700304 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
305 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800306 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700307 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800308 // Don't do this in updateStatus to avoid deadlock over mServiceLock
309 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700310
Ruben Brunkcc776712015-02-17 20:18:47 -0800311 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
312 // to this device until the status changes
313 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700314
Ruben Brunkcc776712015-02-17 20:18:47 -0800315 // Remove cached shim parameters
316 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700317
Ruben Brunkcc776712015-02-17 20:18:47 -0800318 // Remove the client from the list of active clients
319 clientToDisconnect = removeClientLocked(id);
320
321 // Notify the client of disconnection
322 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
323 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700324 }
325
Ruben Brunkcc776712015-02-17 20:18:47 -0800326 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
327 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700328
Ruben Brunkcc776712015-02-17 20:18:47 -0800329 // Disconnect client
330 if (clientToDisconnect.get() != nullptr) {
331 // Ensure not in binder RPC so client disconnect PID checks work correctly
332 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
333 "onDeviceStatusChanged must be called from the camera service process!");
334 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700335 }
336
Ruben Brunkcc776712015-02-17 20:18:47 -0800337 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700338 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
339 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
340 newStatus));
341 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800342 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700343 }
344
Igor Murashkincba2c162013-03-20 15:56:31 -0700345}
346
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800347void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800348 ICameraServiceListener::TorchStatus newStatus) {
349 Mutex::Autolock al(mTorchStatusMutex);
350 onTorchStatusChangedLocked(cameraId, newStatus);
351}
352
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800353void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800354 ICameraServiceListener::TorchStatus newStatus) {
355 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
356 __FUNCTION__, cameraId.string(), newStatus);
357
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800358 ICameraServiceListener::TorchStatus status;
359 status_t res = getTorchStatusLocked(cameraId, &status);
360 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700361 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
362 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800363 return;
364 }
365 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800366 return;
367 }
368
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800369 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800370 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800371 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
372 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800373 return;
374 }
375
Ruben Brunkcc776712015-02-17 20:18:47 -0800376 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700377 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700378 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700379 auto iter = mTorchUidMap.find(cameraId);
380 if (iter != mTorchUidMap.end()) {
381 int oldUid = iter->second.second;
382 int newUid = iter->second.first;
383 BatteryNotifier& notifier(BatteryNotifier::getInstance());
384 if (oldUid != newUid) {
385 // If the UID has changed, log the status and update current UID in mTorchUidMap
386 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
387 notifier.noteFlashlightOff(cameraId, oldUid);
388 }
389 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
390 notifier.noteFlashlightOn(cameraId, newUid);
391 }
392 iter->second.second = newUid;
393 } else {
394 // If the UID has not changed, log the status
395 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
396 notifier.noteFlashlightOn(cameraId, oldUid);
397 } else {
398 notifier.noteFlashlightOff(cameraId, oldUid);
399 }
400 }
401 }
402 }
403
404 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800405 Mutex::Autolock lock(mStatusListenerLock);
406 for (auto& i : mListenerList) {
407 i->onTorchStatusChanged(newStatus, String16{cameraId});
408 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800409 }
410}
411
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700413 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700414 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
415}
416
417int32_t CameraService::getNumberOfCameras(int type) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700418 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700419 switch (type) {
420 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
421 return mNumberOfNormalCameras;
422 case CAMERA_TYPE_ALL:
423 return mNumberOfCameras;
424 default:
425 ALOGW("%s: Unknown camera type %d, returning 0",
426 __FUNCTION__, type);
427 return 0;
428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429}
430
431status_t CameraService::getCameraInfo(int cameraId,
432 struct CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700433 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700434 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700435 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700436 }
437
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
439 return BAD_VALUE;
440 }
441
Iliyan Malchev8951a972011-04-14 16:55:59 -0700442 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700443 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800444 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700445 cameraInfo->facing = info.facing;
446 cameraInfo->orientation = info.orientation;
447 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448}
449
Ruben Brunkcc776712015-02-17 20:18:47 -0800450int CameraService::cameraIdToInt(const String8& cameraId) {
451 errno = 0;
452 size_t pos = 0;
453 int ret = stoi(std::string{cameraId.string()}, &pos);
454 if (errno != 0 || pos != cameraId.size()) {
455 return -1;
456 }
457 return ret;
458}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700459
460status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700461 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700462 status_t ret = OK;
463 struct CameraInfo info;
464 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
465 return ret;
466 }
467
468 CameraMetadata shimInfo;
469 int32_t orientation = static_cast<int32_t>(info.orientation);
470 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
471 return ret;
472 }
473
474 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
475 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
476 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
477 return ret;
478 }
479
Igor Murashkin65d14b92014-06-17 12:03:20 -0700480 CameraParameters shimParams;
481 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
482 // Error logged by callee
483 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700484 }
485
486 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700487 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700488 Vector<int32_t> formats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700489 {
490 shimParams.getSupportedPreviewSizes(/*out*/sizes);
491 shimParams.getSupportedPreviewFormats(/*out*/formats);
492 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700493 }
494
495 // Always include IMPLEMENTATION_DEFINED
496 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
497
498 const size_t INTS_PER_CONFIG = 4;
499
500 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700501 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
502
503 Vector<int32_t> streamConfigs;
504 streamConfigs.setCapacity(streamConfigSize);
505
Ruben Brunkb2119af2014-05-09 19:57:56 -0700506 for (size_t i = 0; i < formats.size(); ++i) {
507 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700508 streamConfigs.add(formats[i]);
509 streamConfigs.add(sizes[j].width);
510 streamConfigs.add(sizes[j].height);
511 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700512 }
513 }
514
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700515 for (size_t i = 0; i < jpegSizes.size(); ++i) {
516 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
517 streamConfigs.add(jpegSizes[i].width);
518 streamConfigs.add(jpegSizes[i].height);
519 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
520 }
521
Ruben Brunkb2119af2014-05-09 19:57:56 -0700522 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700523 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700524 return ret;
525 }
526
527 int64_t fakeMinFrames[0];
528 // TODO: Fixme, don't fake min frame durations.
529 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
530 fakeMinFrames, 0)) != OK) {
531 return ret;
532 }
533
534 int64_t fakeStalls[0];
535 // TODO: Fixme, don't fake stall durations.
536 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
537 fakeStalls, 0)) != OK) {
538 return ret;
539 }
540
541 *cameraInfo = shimInfo;
542 return OK;
543}
544
Zhijun He2b59be82013-09-25 10:14:30 -0700545status_t CameraService::getCameraCharacteristics(int cameraId,
546 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700547 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700548 if (!cameraInfo) {
549 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
550 return BAD_VALUE;
551 }
552
553 if (!mModule) {
554 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
555 return -ENODEV;
556 }
557
Zhijun He2b59be82013-09-25 10:14:30 -0700558 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
559 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
560 return BAD_VALUE;
561 }
562
563 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700564 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800565 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800566 getDeviceVersion(cameraId, &facing) < CAMERA_DEVICE_API_VERSION_3_0) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700567 /**
568 * Backwards compatibility mode for old HALs:
569 * - Convert CameraInfo into static CameraMetadata properties.
570 * - Retrieve cached CameraParameters for this camera. If none exist,
571 * attempt to open CameraClient and retrieve the CameraParameters.
572 * - Convert cached CameraParameters into static CameraMetadata
573 * properties.
574 */
575 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700576
Ruben Brunkb2119af2014-05-09 19:57:56 -0700577 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
578 return ret;
579 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700580
Ruben Brunkb2119af2014-05-09 19:57:56 -0700581 } else {
582 /**
583 * Normal HAL 2.1+ codepath.
584 */
585 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800586 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700587 *cameraInfo = info.static_camera_characteristics;
588 }
Zhijun He2b59be82013-09-25 10:14:30 -0700589
590 return ret;
591}
592
Ruben Brunkcc776712015-02-17 20:18:47 -0800593int CameraService::getCallingPid() {
594 return IPCThreadState::self()->getCallingPid();
595}
596
597int CameraService::getCallingUid() {
598 return IPCThreadState::self()->getCallingUid();
599}
600
601String8 CameraService::getFormattedCurrentTime() {
602 time_t now = time(nullptr);
603 char formattedTime[64];
604 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
605 return String8(formattedTime);
606}
607
608int CameraService::getCameraPriorityFromProcState(int procState) {
609 // Find the priority for the camera usage based on the process state. Higher priority clients
610 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700611 if (procState < 0) {
612 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
613 procState);
614 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800615 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700616 // Treat sleeping TOP processes the same as regular TOP processes, for
617 // access priority. This is important for lock-screen camera launch scenarios
618 if (procState == PROCESS_STATE_TOP_SLEEPING) {
619 procState = PROCESS_STATE_TOP;
620 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700621 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800622}
623
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800624status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700625 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800626 if (!mModule) {
627 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
628 return -ENODEV;
629 }
630
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800631 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
632 return OK;
633}
634
Igor Murashkin634a5152013-02-20 17:15:11 -0800635int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700636 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800637 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800638 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800639 return -1;
640 }
641
642 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800643 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800644 deviceVersion = info.device_version;
645 } else {
646 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
647 }
648
649 if (facing) {
650 *facing = info.facing;
651 }
652
653 return deviceVersion;
654}
655
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700656status_t CameraService::filterGetInfoErrorCode(status_t err) {
657 switch(err) {
658 case NO_ERROR:
659 case -EINVAL:
660 return err;
661 default:
662 break;
663 }
664 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800665}
666
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800667bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700668 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800669 vendor_tag_ops_t vOps = vendor_tag_ops_t();
670
671 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800672 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800673 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
674 return false;
675 }
676
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800677 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800678
679 // Ensure all vendor operations are present
680 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
681 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
682 vOps.get_tag_type == NULL) {
683 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
684 , __FUNCTION__);
685 return false;
686 }
687
688 // Read all vendor tag definitions into a descriptor
689 sp<VendorTagDescriptor> desc;
690 status_t res;
691 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
692 != OK) {
693 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
694 "received error %s (%d). Camera clients will not be able to use"
695 "vendor tags", __FUNCTION__, strerror(res), res);
696 return false;
697 }
698
699 // Set the global descriptor to use with camera metadata
700 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
701 return true;
702}
703
Ruben Brunkcc776712015-02-17 20:18:47 -0800704status_t CameraService::makeClient(const sp<CameraService>& cameraService,
705 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
706 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
707 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
708 /*out*/sp<BasicClient>* client) {
709
710 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
711 int id = cameraIdToInt(cameraId);
712 if (id == -1) {
713 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
714 cameraId.string());
715 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700716 }
717
Ruben Brunkcc776712015-02-17 20:18:47 -0800718 if (halVersion < 0 || halVersion == deviceVersion) {
719 // Default path: HAL version is unspecified by caller, create CameraClient
720 // based on device version reported by the HAL.
721 switch(deviceVersion) {
722 case CAMERA_DEVICE_API_VERSION_1_0:
723 if (effectiveApiLevel == API_1) { // Camera1 API route
724 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
725 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
726 clientPid, clientUid, getpid(), legacyMode);
727 } else { // Camera2 API route
728 ALOGW("Camera using old HAL version: %d", deviceVersion);
729 return -EOPNOTSUPP;
730 }
731 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800732 case CAMERA_DEVICE_API_VERSION_3_0:
733 case CAMERA_DEVICE_API_VERSION_3_1:
734 case CAMERA_DEVICE_API_VERSION_3_2:
735 case CAMERA_DEVICE_API_VERSION_3_3:
736 if (effectiveApiLevel == API_1) { // Camera1 API route
737 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
738 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
739 clientPid, clientUid, servicePid, legacyMode);
740 } else { // Camera2 API route
741 sp<ICameraDeviceCallbacks> tmp =
742 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
743 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
744 facing, clientPid, clientUid, servicePid);
745 }
746 break;
747 default:
748 // Should not be reachable
749 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
750 return INVALID_OPERATION;
751 }
752 } else {
753 // A particular HAL version is requested by caller. Create CameraClient
754 // based on the requested HAL version.
755 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
756 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
757 // Only support higher HAL version device opened as HAL1.0 device.
758 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
759 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
760 clientPid, clientUid, servicePid, legacyMode);
761 } else {
762 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
763 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
764 " opened as HAL %x device", halVersion, deviceVersion,
765 CAMERA_DEVICE_API_VERSION_1_0);
766 return INVALID_OPERATION;
767 }
768 }
769 return NO_ERROR;
770}
771
Ruben Brunk6267b532015-04-30 17:44:07 -0700772String8 CameraService::toString(std::set<userid_t> intSet) {
773 String8 s("");
774 bool first = true;
775 for (userid_t i : intSet) {
776 if (first) {
777 s.appendFormat("%d", i);
778 first = false;
779 } else {
780 s.appendFormat(", %d", i);
781 }
782 }
783 return s;
784}
785
Ruben Brunkcc776712015-02-17 20:18:47 -0800786status_t CameraService::initializeShimMetadata(int cameraId) {
787 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700788
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800789 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800790 String8 id = String8::format("%d", cameraId);
791 status_t ret = NO_ERROR;
792 sp<Client> tmp = nullptr;
793 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800794 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid,
795 USE_CALLING_PID, API_1, false, true, tmp)) != NO_ERROR) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800796 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
797 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700798 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800799 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700800}
801
Igor Murashkin65d14b92014-06-17 12:03:20 -0700802status_t CameraService::getLegacyParametersLazy(int cameraId,
803 /*out*/
804 CameraParameters* parameters) {
805
806 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
807
808 status_t ret = 0;
809
810 if (parameters == NULL) {
811 ALOGE("%s: parameters must not be null", __FUNCTION__);
812 return BAD_VALUE;
813 }
814
Ruben Brunkcc776712015-02-17 20:18:47 -0800815 String8 id = String8::format("%d", cameraId);
816
817 // Check if we already have parameters
818 {
819 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700820 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800821 auto cameraState = getCameraState(id);
822 if (cameraState == nullptr) {
823 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
824 return BAD_VALUE;
825 }
826 CameraParameters p = cameraState->getShimParams();
827 if (!p.isEmpty()) {
828 *parameters = p;
829 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700830 }
831 }
832
Ruben Brunkcc776712015-02-17 20:18:47 -0800833 int64_t token = IPCThreadState::self()->clearCallingIdentity();
834 ret = initializeShimMetadata(cameraId);
835 IPCThreadState::self()->restoreCallingIdentity(token);
836 if (ret != NO_ERROR) {
837 // Error already logged by callee
838 return ret;
839 }
840
841 // Check for parameters again
842 {
843 // Scope for service lock
844 Mutex::Autolock lock(mServiceLock);
845 auto cameraState = getCameraState(id);
846 if (cameraState == nullptr) {
847 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
848 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700849 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800850 CameraParameters p = cameraState->getShimParams();
851 if (!p.isEmpty()) {
852 *parameters = p;
853 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700854 }
855 }
856
Ruben Brunkcc776712015-02-17 20:18:47 -0800857 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
858 __FUNCTION__);
859 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700860}
861
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800862// Can camera service trust the caller based on the calling UID?
863static bool isTrustedCallingUid(uid_t uid) {
864 switch (uid) {
865 case AID_MEDIA: // mediaserver
866 case AID_CAMERASERVER: // cameraserver
867 return true;
868 default:
869 return false;
870 }
871}
872
873status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid,
874 /*inout*/int& clientPid) const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800875
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500877
Christopher Wileyce761d12016-02-16 10:15:00 -0800878#if !defined(__BRILLO__)
879 status_t allowed = validateClientPermissionsLocked(cameraId, clientUid, clientPid);
880 if (allowed != OK) {
881 return allowed;
882 }
883#endif // defined(__BRILLO__)
884
Iliyan Malchev8951a972011-04-14 16:55:59 -0700885 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800886 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
887 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700888 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700889 }
890
Ruben Brunkcc776712015-02-17 20:18:47 -0800891 if (getCameraState(cameraId) == nullptr) {
892 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
893 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700894 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800897 return checkIfDeviceIsUsable(cameraId);
898}
899
Christopher Wileyce761d12016-02-16 10:15:00 -0800900status_t CameraService::validateClientPermissionsLocked(const String8& cameraId, int& clientUid,
901 int& clientPid) const {
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800902 int callingPid = getCallingPid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800903 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800905 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800907 clientUid = callingUid;
908 } else if (!isTrustedCallingUid(callingUid)) {
909 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
910 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
911 return PERMISSION_DENIED;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 }
913
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800914 // Check if we can trust clientPid
915 if (clientPid == USE_CALLING_PID) {
916 clientPid = callingPid;
917 } else if (!isTrustedCallingUid(callingUid)) {
918 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
919 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
920 return PERMISSION_DENIED;
921 }
922
923 // If it's not calling from cameraserver, check the permission.
924 if (callingPid != getpid() &&
925 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
926 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
927 return PERMISSION_DENIED;
928 }
929
930 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
931 // connected to camera service directly.
932 clientPid = callingPid;
933
Ruben Brunkcc776712015-02-17 20:18:47 -0800934 // Check device policy for this camera
Ruben Brunk6267b532015-04-30 17:44:07 -0700935 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800936
Ruben Brunka8ca9152015-04-07 14:23:40 -0700937 // Only allow clients who are being used by the current foreground device user, unless calling
938 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700939 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
940 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
941 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
942 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700943 return PERMISSION_DENIED;
944 }
945
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800946 return OK;
Ruben Brunkcc776712015-02-17 20:18:47 -0800947}
948
949status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
950 auto cameraState = getCameraState(cameraId);
951 int callingPid = getCallingPid();
952 if (cameraState == nullptr) {
953 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
954 cameraId.string());
955 return -ENODEV;
956 }
957
958 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700959 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800960 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
961 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700962 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700963 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800964 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
965 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700966 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700967 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700968
Ruben Brunkcc776712015-02-17 20:18:47 -0800969 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800970}
971
Ruben Brunkcc776712015-02-17 20:18:47 -0800972void CameraService::finishConnectLocked(const sp<BasicClient>& client,
973 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800974
Ruben Brunkcc776712015-02-17 20:18:47 -0800975 // Make a descriptor for the incoming client
976 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
977 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
978
979 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
980 String8(client->getPackageName()));
981
982 if (evicted.size() > 0) {
983 // This should never happen - clients should already have been removed in disconnect
984 for (auto& i : evicted) {
985 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
986 __FUNCTION__, i->getKey().string());
987 }
988
989 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
990 __FUNCTION__);
991 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700992
993 // And register a death notification for the client callback. Do
994 // this last to avoid Binder policy where a nested Binder
995 // transaction might be pre-empted to service the client death
996 // notification if the client process dies before linkToDeath is
997 // invoked.
998 sp<IBinder> remoteCallback = client->getRemote();
999 if (remoteCallback != nullptr) {
1000 remoteCallback->linkToDeath(this);
1001 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001002}
1003
1004status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1005 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1006 /*out*/
1007 sp<BasicClient>* client,
1008 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001009 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001010 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001011 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001012 DescriptorPtr clientDescriptor;
1013 {
1014 if (effectiveApiLevel == API_1) {
1015 // If we are using API1, any existing client for this camera ID with the same remote
1016 // should be returned rather than evicted to allow MediaRecorder to work properly.
1017
1018 auto current = mActiveClientManager.get(cameraId);
1019 if (current != nullptr) {
1020 auto clientSp = current->getValue();
1021 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001022 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1023 ALOGW("CameraService connect called from same client, but with a different"
1024 " API level, evicting prior client...");
1025 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001026 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001027 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001028 *client = clientSp;
1029 return NO_ERROR;
1030 }
1031 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001032 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001033 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001034
Ruben Brunkcc776712015-02-17 20:18:47 -08001035 // Return error if the device was unplugged or removed by the HAL for some reason
1036 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1037 return ret;
1038 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001039
Ruben Brunkcc776712015-02-17 20:18:47 -08001040 // Get current active client PIDs
1041 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1042 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001043
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001044 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1045 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1046 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1047 // not have an out-of-class definition.
1048 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001049
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 // Get priorites of all active PIDs
1051 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1052 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001053
Ruben Brunkcc776712015-02-17 20:18:47 -08001054 // Update all active clients' priorities
1055 std::map<int,int> pidToPriorityMap;
1056 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1057 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1058 }
1059 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001060
Ruben Brunkcc776712015-02-17 20:18:47 -08001061 // Get state for the given cameraId
1062 auto state = getCameraState(cameraId);
1063 if (state == nullptr) {
1064 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1065 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001066 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001067 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001068
1069 // Make descriptor for incoming client
1070 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1071 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1072 state->getConflicting(),
1073 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1074
1075 // Find clients that would be evicted
1076 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1077
1078 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1079 // background, so we cannot do evictions
1080 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1081 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1082 " priority).", clientPid);
1083
1084 sp<BasicClient> clientSp = clientDescriptor->getValue();
1085 String8 curTime = getFormattedCurrentTime();
1086 auto incompatibleClients =
1087 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1088
1089 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001090 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001091 cameraId.string(), packageName.string(), clientPid,
1092 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1093
1094 for (auto& i : incompatibleClients) {
1095 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1096 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1097 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1098 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001099 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1100 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1101 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1102 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001103 }
1104
1105 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001106 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001107 mEventLog.add(msg);
1108
1109 return -EBUSY;
1110 }
1111
1112 for (auto& i : evicted) {
1113 sp<BasicClient> clientSp = i->getValue();
1114 if (clientSp.get() == nullptr) {
1115 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1116
1117 // TODO: Remove this
1118 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1119 __FUNCTION__);
1120 mActiveClientManager.remove(i);
1121 continue;
1122 }
1123
1124 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1125 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001126 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001127
Ruben Brunkcc776712015-02-17 20:18:47 -08001128 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001129 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1130 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1131 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1133 i->getOwnerId(), i->getPriority(), cameraId.string(),
1134 packageName.string(), clientPid,
1135 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1136
1137 // Notify the client of disconnection
1138 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1139 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001140 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001141 }
1142
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1144 // other clients from connecting in mServiceLockWrapper if held
1145 mServiceLock.unlock();
1146
1147 // Clear caller identity temporarily so client disconnect PID checks work correctly
1148 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1149
1150 // Destroy evicted clients
1151 for (auto& i : evictedClients) {
1152 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001153 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001154 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001155
1156 IPCThreadState::self()->restoreCallingIdentity(token);
1157
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001158 for (const auto& i : evictedClients) {
1159 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1160 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1161 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1162 if (ret == TIMED_OUT) {
1163 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1164 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1165 mActiveClientManager.toString().string());
1166 return -EBUSY;
1167 }
1168 if (ret != NO_ERROR) {
1169 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1170 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1171 ret, mActiveClientManager.toString().string());
1172 return ret;
1173 }
1174 }
1175
1176 evictedClients.clear();
1177
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 // Once clients have been disconnected, relock
1179 mServiceLock.lock();
1180
1181 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1182 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1183 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001184 }
1185
Ruben Brunkcc776712015-02-17 20:18:47 -08001186 *partial = clientDescriptor;
1187 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001188}
1189
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001190status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001191 const sp<ICameraClient>& cameraClient,
1192 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001193 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001194 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001195 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001196 /*out*/
1197 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001198
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001199 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001200 status_t ret = NO_ERROR;
1201 String8 id = String8::format("%d", cameraId);
1202 sp<Client> client = nullptr;
1203 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001204 clientPackageName, clientUid, clientPid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001205
Ruben Brunkcc776712015-02-17 20:18:47 -08001206 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001207 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001208 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001209 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 }
1211
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001212 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001213 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214}
1215
Zhijun Heb10cdad2014-06-16 16:38:35 -07001216status_t CameraService::connectLegacy(
1217 const sp<ICameraClient>& cameraClient,
1218 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001219 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001220 int clientUid,
1221 /*out*/
1222 sp<ICamera>& device) {
1223
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001224 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001225 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001226 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001227 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001228 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001229 /*
1230 * Either the HAL version is unspecified in which case this just creates
1231 * a camera client selected by the latest device version, or
1232 * it's a particular version in which case the HAL must supported
1233 * the open_legacy call
1234 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001235 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001236 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001237 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001238 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001239 return INVALID_OPERATION;
1240 }
1241
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001243 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001244 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001245 clientUid, USE_CALLING_PID, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001246
Ruben Brunkcc776712015-02-17 20:18:47 -08001247 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001248 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001249 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001250 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001251 }
1252
Zhijun Heb10cdad2014-06-16 16:38:35 -07001253 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001254 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001255}
1256
Ruben Brunkcc776712015-02-17 20:18:47 -08001257status_t CameraService::connectDevice(
1258 const sp<ICameraDeviceCallbacks>& cameraCb,
1259 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001260 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 int clientUid,
1262 /*out*/
1263 sp<ICameraDeviceUser>& device) {
1264
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001265 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001266 status_t ret = NO_ERROR;
1267 String8 id = String8::format("%d", cameraId);
1268 sp<CameraDeviceClient> client = nullptr;
1269 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001270 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, USE_CALLING_PID,
1271 API_2, false, false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001272
1273 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001274 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001275 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001276 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001277 }
1278
Ruben Brunkcc776712015-02-17 20:18:47 -08001279 device = client;
1280 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001281}
1282
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001283status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1284 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001285
1286 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001287 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001288 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001289 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001290 }
1291
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001292 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001293 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001294
1295 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001296 auto state = getCameraState(id);
1297 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001298 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 return -EINVAL;
1300 }
1301
1302 ICameraServiceListener::Status cameraStatus = state->getStatus();
1303 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1304 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001305 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001306 return -EINVAL;
1307 }
1308
1309 {
1310 Mutex::Autolock al(mTorchStatusMutex);
1311 ICameraServiceListener::TorchStatus status;
1312 status_t res = getTorchStatusLocked(id, &status);
1313 if (res) {
1314 ALOGE("%s: getting current torch status failed for camera %s",
1315 __FUNCTION__, id.string());
1316 return -EINVAL;
1317 }
1318
1319 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001320 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001321 ALOGE("%s: torch mode of camera %s is not available because "
1322 "camera is in use", __FUNCTION__, id.string());
1323 return -EBUSY;
1324 } else {
1325 ALOGE("%s: torch mode of camera %s is not available due to "
1326 "insufficient resources", __FUNCTION__, id.string());
1327 return -EUSERS;
1328 }
1329 }
1330 }
1331
Ruben Brunk99e69712015-05-26 17:25:07 -07001332 {
1333 // Update UID map - this is used in the torch status changed callbacks, so must be done
1334 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001335 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001336 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1337 mTorchUidMap[id].first = uid;
1338 mTorchUidMap[id].second = uid;
1339 } else {
1340 // Set the pending UID
1341 mTorchUidMap[id].first = uid;
1342 }
1343 }
1344
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001345 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001346
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001347 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001348 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1349 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001350 return res;
1351 }
1352
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001353 {
1354 // update the link to client's death
1355 Mutex::Autolock al(mTorchClientMapMutex);
1356 ssize_t index = mTorchClientMap.indexOfKey(id);
1357 if (enabled) {
1358 if (index == NAME_NOT_FOUND) {
1359 mTorchClientMap.add(id, clientBinder);
1360 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001361 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001362 mTorchClientMap.replaceValueAt(index, clientBinder);
1363 }
1364 clientBinder->linkToDeath(this);
1365 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001366 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001367 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001368 }
1369
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001370 return OK;
1371}
1372
Ruben Brunk6267b532015-04-30 17:44:07 -07001373void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001374 ATRACE_CALL();
1375
Ruben Brunk36597b22015-03-20 22:15:57 -07001376 switch(eventId) {
1377 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001378 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001379 break;
1380 }
1381 case ICameraService::NO_EVENT:
1382 default: {
1383 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1384 eventId);
1385 break;
1386 }
1387 }
1388}
1389
Ruben Brunk99e69712015-05-26 17:25:07 -07001390status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001391 ATRACE_CALL();
1392
Igor Murashkinbfc99152013-02-27 12:55:20 -08001393 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001394
Ruben Brunk3450ba72015-06-16 11:00:37 -07001395 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001396 ALOGE("%s: Listener must not be null", __FUNCTION__);
1397 return BAD_VALUE;
1398 }
1399
Igor Murashkinbfc99152013-02-27 12:55:20 -08001400 Mutex::Autolock lock(mServiceLock);
1401
Ruben Brunkcc776712015-02-17 20:18:47 -08001402 {
1403 Mutex::Autolock lock(mStatusListenerLock);
1404 for (auto& it : mListenerList) {
1405 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1406 ALOGW("%s: Tried to add listener %p which was already subscribed",
1407 __FUNCTION__, listener.get());
1408 return ALREADY_EXISTS;
1409 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001410 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001411
1412 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001413 }
1414
Igor Murashkinbfc99152013-02-27 12:55:20 -08001415
Igor Murashkincba2c162013-03-20 15:56:31 -07001416 /* Immediately signal current status to this listener only */
1417 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001418 Mutex::Autolock lock(mCameraStatesLock);
1419 for (auto& i : mCameraStates) {
1420 // TODO: Update binder to use String16 for camera IDs and remove;
1421 int id = cameraIdToInt(i.first);
1422 if (id == -1) continue;
1423
1424 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001425 }
1426 }
1427
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001428 /* Immediately signal current torch status to this listener only */
1429 {
1430 Mutex::Autolock al(mTorchStatusMutex);
1431 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001432 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1433 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001434 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001435 }
1436
Igor Murashkinbfc99152013-02-27 12:55:20 -08001437 return OK;
1438}
Ruben Brunkcc776712015-02-17 20:18:47 -08001439
1440status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001441 ATRACE_CALL();
1442
Igor Murashkinbfc99152013-02-27 12:55:20 -08001443 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1444
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001445 if (listener == 0) {
1446 ALOGE("%s: Listener must not be null", __FUNCTION__);
1447 return BAD_VALUE;
1448 }
1449
Igor Murashkinbfc99152013-02-27 12:55:20 -08001450 Mutex::Autolock lock(mServiceLock);
1451
Ruben Brunkcc776712015-02-17 20:18:47 -08001452 {
1453 Mutex::Autolock lock(mStatusListenerLock);
1454 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1455 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1456 mListenerList.erase(it);
1457 return OK;
1458 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001459 }
1460 }
1461
1462 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1463 __FUNCTION__, listener.get());
1464
1465 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001466}
1467
Ruben Brunkcc776712015-02-17 20:18:47 -08001468status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001469
1470 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001471 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1472
1473 if (parameters == NULL) {
1474 ALOGE("%s: parameters must not be null", __FUNCTION__);
1475 return BAD_VALUE;
1476 }
1477
1478 status_t ret = 0;
1479
1480 CameraParameters shimParams;
1481 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1482 // Error logged by caller
1483 return ret;
1484 }
1485
1486 String8 shimParamsString8 = shimParams.flatten();
1487 String16 shimParamsString16 = String16(shimParamsString8);
1488
1489 *parameters = shimParamsString16;
1490
1491 return OK;
1492}
1493
1494status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001495 ATRACE_CALL();
1496
Igor Murashkin65d14b92014-06-17 12:03:20 -07001497 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1498
1499 switch (apiVersion) {
1500 case API_VERSION_1:
1501 case API_VERSION_2:
1502 break;
1503 default:
1504 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1505 return BAD_VALUE;
1506 }
1507
1508 int facing = -1;
1509 int deviceVersion = getDeviceVersion(cameraId, &facing);
1510
1511 switch(deviceVersion) {
1512 case CAMERA_DEVICE_API_VERSION_1_0:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001513 case CAMERA_DEVICE_API_VERSION_3_0:
1514 case CAMERA_DEVICE_API_VERSION_3_1:
1515 if (apiVersion == API_VERSION_2) {
1516 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1517 __FUNCTION__, cameraId);
1518 return -EOPNOTSUPP;
1519 } else { // if (apiVersion == API_VERSION_1) {
1520 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1521 __FUNCTION__, cameraId);
1522 return OK;
1523 }
1524 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001525 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001526 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1527 __FUNCTION__, cameraId);
1528 return OK;
1529 case -1:
1530 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1531 return BAD_VALUE;
1532 default:
1533 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1534 return INVALID_OPERATION;
1535 }
1536
1537 return OK;
1538}
1539
Ruben Brunkcc776712015-02-17 20:18:47 -08001540void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001541 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001542 for (auto& i : mActiveClientManager.getAll()) {
1543 auto clientSp = i->getValue();
1544 if (clientSp.get() == client) {
1545 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001546 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001547 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001548}
1549
Ruben Brunkcc776712015-02-17 20:18:47 -08001550bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1551 const int callingPid = getCallingPid();
1552 const int servicePid = getpid();
1553 bool ret = false;
1554 {
1555 // Acquire mServiceLock and prevent other clients from connecting
1556 std::unique_ptr<AutoConditionLock> lock =
1557 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001558
Igor Murashkin634a5152013-02-20 17:15:11 -08001559
Ruben Brunkcc776712015-02-17 20:18:47 -08001560 std::vector<sp<BasicClient>> evicted;
1561 for (auto& i : mActiveClientManager.getAll()) {
1562 auto clientSp = i->getValue();
1563 if (clientSp.get() == nullptr) {
1564 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1565 mActiveClientManager.remove(i);
1566 continue;
1567 }
1568 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1569 callingPid == clientSp->getClientPid())) {
1570 mActiveClientManager.remove(i);
1571 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001572
Ruben Brunkcc776712015-02-17 20:18:47 -08001573 // Notify the client of disconnection
1574 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1575 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001576 }
1577 }
1578
Ruben Brunkcc776712015-02-17 20:18:47 -08001579 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1580 // other clients from connecting in mServiceLockWrapper if held
1581 mServiceLock.unlock();
1582
Ruben Brunk36597b22015-03-20 22:15:57 -07001583 // Do not clear caller identity, remote caller should be client proccess
1584
Ruben Brunkcc776712015-02-17 20:18:47 -08001585 for (auto& i : evicted) {
1586 if (i.get() != nullptr) {
1587 i->disconnect();
1588 ret = true;
1589 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001590 }
1591
Ruben Brunkcc776712015-02-17 20:18:47 -08001592 // Reacquire mServiceLock
1593 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001594
Ruben Brunkcc776712015-02-17 20:18:47 -08001595 } // lock is destroyed, allow further connect calls
1596
1597 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001598}
1599
Igor Murashkinecf17e82012-10-02 16:05:11 -07001600
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001601/**
1602 * Check camera capabilities, such as support for basic color operation
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001603 * Also check that the device HAL version is still in support
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001604 */
1605int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
Yin-Chia Yeh654b4bf2015-12-08 12:19:31 -08001606 // device_version undefined in CAMERA_MODULE_API_VERSION_1_0,
1607 // All CAMERA_MODULE_API_VERSION_1_0 devices are backward-compatible
1608 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
1609 // Verify the device version is in the supported range
1610 switch (info.device_version) {
1611 case CAMERA_DEVICE_API_VERSION_1_0:
1612 case CAMERA_DEVICE_API_VERSION_3_0:
1613 case CAMERA_DEVICE_API_VERSION_3_1:
1614 case CAMERA_DEVICE_API_VERSION_3_2:
1615 case CAMERA_DEVICE_API_VERSION_3_3:
1616 // in support
1617 break;
1618 case CAMERA_DEVICE_API_VERSION_2_0:
1619 case CAMERA_DEVICE_API_VERSION_2_1:
1620 // no longer supported
1621 default:
1622 ALOGE("%s: Device %d has HAL version %x, which is not supported",
1623 __FUNCTION__, id, info.device_version);
1624 String8 msg = String8::format(
1625 "Unsupported device HAL version %x for device %d",
1626 info.device_version, id);
1627 logServiceError(msg.string(), NO_INIT);
1628 return NO_INIT;
1629 }
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001630 }
1631
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001632 // Assume all devices pre-v3.3 are backward-compatible
1633 bool isBackwardCompatible = true;
1634 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1635 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1636 isBackwardCompatible = false;
1637 status_t res;
1638 camera_metadata_ro_entry_t caps;
1639 res = find_camera_metadata_ro_entry(
1640 info.static_camera_characteristics,
1641 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1642 &caps);
1643 if (res != 0) {
1644 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1645 __FUNCTION__, id);
1646 caps.count = 0;
1647 }
1648 for (size_t i = 0; i < caps.count; i++) {
1649 if (caps.data.u8[i] ==
1650 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1651 isBackwardCompatible = true;
1652 break;
1653 }
1654 }
1655 }
1656
1657 if (!isBackwardCompatible) {
1658 mNumberOfNormalCameras--;
1659 *latestStrangeCameraId = id;
1660 } else {
1661 if (id > *latestStrangeCameraId) {
1662 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1663 "This is not allowed due backward-compatibility requirements",
1664 __FUNCTION__, id, *latestStrangeCameraId);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001665 logServiceError("Invalid order of camera devices", NO_INIT);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001666 mNumberOfCameras = 0;
1667 mNumberOfNormalCameras = 0;
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001668 return NO_INIT;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001669 }
1670 }
1671 return OK;
1672}
1673
Ruben Brunkcc776712015-02-17 20:18:47 -08001674std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1675 const String8& cameraId) const {
1676 std::shared_ptr<CameraState> state;
1677 {
1678 Mutex::Autolock lock(mCameraStatesLock);
1679 auto iter = mCameraStates.find(cameraId);
1680 if (iter != mCameraStates.end()) {
1681 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682 }
1683 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001684 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685}
1686
Ruben Brunkcc776712015-02-17 20:18:47 -08001687sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1688 // Remove from active clients list
1689 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1690 if (clientDescriptorPtr == nullptr) {
1691 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1692 cameraId.string());
1693 return sp<BasicClient>{nullptr};
1694 }
1695
1696 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001697}
1698
Ruben Brunk6267b532015-04-30 17:44:07 -07001699void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001700 // Acquire mServiceLock and prevent other clients from connecting
1701 std::unique_ptr<AutoConditionLock> lock =
1702 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1703
Ruben Brunk6267b532015-04-30 17:44:07 -07001704 std::set<userid_t> newAllowedUsers;
1705 for (size_t i = 0; i < length; i++) {
1706 if (newUserId[i] < 0) {
1707 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1708 __FUNCTION__, newUserId[i]);
1709 return;
1710 }
1711 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001712 }
1713
Ruben Brunka8ca9152015-04-07 14:23:40 -07001714
Ruben Brunk6267b532015-04-30 17:44:07 -07001715 if (newAllowedUsers == mAllowedUsers) {
1716 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1717 return;
1718 }
1719
1720 logUserSwitch(mAllowedUsers, newAllowedUsers);
1721
1722 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001723
1724 // Current user has switched, evict all current clients.
1725 std::vector<sp<BasicClient>> evicted;
1726 for (auto& i : mActiveClientManager.getAll()) {
1727 auto clientSp = i->getValue();
1728
1729 if (clientSp.get() == nullptr) {
1730 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1731 continue;
1732 }
1733
Ruben Brunk6267b532015-04-30 17:44:07 -07001734 // Don't evict clients that are still allowed.
1735 uid_t clientUid = clientSp->getClientUid();
1736 userid_t clientUserId = multiuser_get_user_id(clientUid);
1737 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1738 continue;
1739 }
1740
Ruben Brunk36597b22015-03-20 22:15:57 -07001741 evicted.push_back(clientSp);
1742
1743 String8 curTime = getFormattedCurrentTime();
1744
1745 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1746 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001747
Ruben Brunk36597b22015-03-20 22:15:57 -07001748 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001749 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001750 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001751 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1752 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001753
1754 }
1755
1756 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1757 // blocking other clients from connecting in mServiceLockWrapper if held.
1758 mServiceLock.unlock();
1759
1760 // Clear caller identity temporarily so client disconnect PID checks work correctly
1761 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1762
1763 for (auto& i : evicted) {
1764 i->disconnect();
1765 }
1766
1767 IPCThreadState::self()->restoreCallingIdentity(token);
1768
1769 // Reacquire mServiceLock
1770 mServiceLock.lock();
1771}
Ruben Brunkcc776712015-02-17 20:18:47 -08001772
Ruben Brunka8ca9152015-04-07 14:23:40 -07001773void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001774 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001775 Mutex::Autolock l(mLogLock);
1776 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777}
1778
Ruben Brunka8ca9152015-04-07 14:23:40 -07001779void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001780 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001781 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001782 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001783 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001784}
1785
1786void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001787 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001788 // Log the clients evicted
1789 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001790 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001791}
1792
1793void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001794 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001795 // Log the client rejected
1796 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001797 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001798}
1799
Ruben Brunk6267b532015-04-30 17:44:07 -07001800void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1801 const std::set<userid_t>& newUserIds) {
1802 String8 newUsers = toString(newUserIds);
1803 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001804 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001805 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1806 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001807}
1808
1809void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1810 // Log the device removal
1811 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1812}
1813
1814void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1815 // Log the device removal
1816 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1817}
1818
1819void CameraService::logClientDied(int clientPid, const char* reason) {
1820 // Log the device removal
1821 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001822}
1823
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001824void CameraService::logServiceError(const char* msg, int errorCode) {
1825 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001826 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001827}
1828
Ruben Brunk36597b22015-03-20 22:15:57 -07001829status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1830 uint32_t flags) {
1831
1832 const int pid = getCallingPid();
1833 const int selfPid = getpid();
1834
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 // Permission checks
1836 switch (code) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001837 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1838 if (pid != selfPid) {
1839 // Ensure we're being called by system_server, or similar process with
1840 // permissions to notify the camera service about system events
1841 if (!checkCallingPermission(
1842 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1843 const int uid = getCallingUid();
1844 ALOGE("Permission Denial: cannot send updates to camera service about system"
1845 " events from pid=%d, uid=%d", pid, uid);
1846 return PERMISSION_DENIED;
1847 }
1848 }
1849 break;
1850 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 }
1852
1853 return BnCameraService::onTransact(code, data, reply, flags);
1854}
1855
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856// We share the media players for shutter and recording sound for all clients.
1857// A reference count is kept to determine when we will actually release the
1858// media players.
1859
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001860MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001862 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001863 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 mp->prepare();
1865 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001866 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 return NULL;
1868 }
1869 return mp;
1870}
1871
1872void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001873 ATRACE_CALL();
1874
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 Mutex::Autolock lock(mSoundLock);
1876 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1877 if (mSoundRef++) return;
1878
1879 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001880 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1881 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882}
1883
1884void CameraService::releaseSound() {
1885 Mutex::Autolock lock(mSoundLock);
1886 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1887 if (--mSoundRef) return;
1888
1889 for (int i = 0; i < NUM_SOUNDS; i++) {
1890 if (mSoundPlayer[i] != 0) {
1891 mSoundPlayer[i]->disconnect();
1892 mSoundPlayer[i].clear();
1893 }
1894 }
1895}
1896
1897void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001898 ATRACE_CALL();
1899
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900 LOG1("playSound(%d)", kind);
1901 Mutex::Autolock lock(mSoundLock);
1902 sp<MediaPlayer> player = mSoundPlayer[kind];
1903 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001904 player->seekTo(0);
1905 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 }
1907}
1908
1909// ----------------------------------------------------------------------------
1910
1911CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001912 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001913 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001914 int cameraId, int cameraFacing,
1915 int clientPid, uid_t clientUid,
1916 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001917 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001918 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001919 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001920 cameraId, cameraFacing,
1921 clientPid, clientUid,
1922 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001923{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001925 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001927 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001930
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001931 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932}
1933
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934// tear down the client
1935CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001936 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001937 mDestructionStarted = true;
1938
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001939 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001940 // unconditionally disconnect. function is idempotent
1941 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942}
1943
Igor Murashkin634a5152013-02-20 17:15:11 -08001944CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001945 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001946 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001947 int cameraId, int cameraFacing,
1948 int clientPid, uid_t clientUid,
1949 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001950 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001951{
1952 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001953 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001954 mCameraId = cameraId;
1955 mCameraFacing = cameraFacing;
1956 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001957 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001958 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001959 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001960 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08001961
1962 // In some cases the calling code has no access to the package it runs under.
1963 // For example, NDK camera API.
1964 // In this case we will get the packages for the calling UID and pick the first one
1965 // for attributing the app op. This will work correctly for runtime permissions
1966 // as for legacy apps we will toggle the app op for all packages in the UID.
1967 // The caveat is that the operation may be attributed to the wrong package and
1968 // stats based on app ops may be slightly off.
1969 if (mClientPackageName.size() <= 0) {
1970 sp<IServiceManager> sm = defaultServiceManager();
1971 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
1972 if (binder == 0) {
1973 ALOGE("Cannot get permission service");
1974 // Leave mClientPackageName unchanged (empty) and the further interaction
1975 // with camera will fail in BasicClient::startCameraOps
1976 return;
1977 }
1978
1979 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
1980 Vector<String16> packages;
1981
1982 permCtrl->getPackagesForUid(mClientUid, packages);
1983
1984 if (packages.isEmpty()) {
1985 ALOGE("No packages for calling UID");
1986 // Leave mClientPackageName unchanged (empty) and the further interaction
1987 // with camera will fail in BasicClient::startCameraOps
1988 return;
1989 }
1990 mClientPackageName = packages[0];
1991 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001992}
1993
1994CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001995 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001996 mDestructionStarted = true;
1997}
1998
1999void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07002000 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002001 return;
2002 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002003 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002004
2005 mCameraService->removeByClient(this);
2006 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002007 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08002008
2009 sp<IBinder> remote = getRemote();
2010 if (remote != nullptr) {
2011 remote->unlinkToDeath(mCameraService);
2012 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002013
2014 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08002015 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
2016
Igor Murashkincba2c162013-03-20 15:56:31 -07002017 // client shouldn't be able to call into us anymore
2018 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08002019}
2020
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002021status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2022 // No dumping of clients directly over Binder,
2023 // must go through CameraService::dump
2024 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2025 IPCThreadState::self()->getCallingUid(), NULL, 0);
2026 return OK;
2027}
2028
Ruben Brunkcc776712015-02-17 20:18:47 -08002029String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002030 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002031}
2032
2033
2034int CameraService::BasicClient::getClientPid() const {
2035 return mClientPid;
2036}
2037
Ruben Brunk6267b532015-04-30 17:44:07 -07002038uid_t CameraService::BasicClient::getClientUid() const {
2039 return mClientUid;
2040}
2041
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002042bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2043 // Defaults to API2.
2044 return level == API_2;
2045}
2046
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002047status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002048 ATRACE_CALL();
2049
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002050 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002051 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002052 mOpsCallback = new OpsCallback(this);
2053
Igor Murashkine6800ce2013-03-04 17:25:57 -08002054 {
2055 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002056 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002057 }
2058
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002059 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002060 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002061 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002062 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002063
Svetoslav28e8ef72015-05-11 19:21:31 -07002064 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002065 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002066 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002067 return PERMISSION_DENIED;
2068 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002069
Svetoslav28e8ef72015-05-11 19:21:31 -07002070 if (res == AppOpsManager::MODE_IGNORED) {
2071 ALOGI("Camera %d: Access for \"%s\" has been restricted",
2072 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002073 // Return the same error as for device policy manager rejection
2074 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002075 }
2076
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002077 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002078
2079 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2080 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002081 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002082
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002083 // Transition device state to OPEN
2084 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2085 String8::format("%d", mCameraId));
2086
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002087 return OK;
2088}
2089
2090status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002091 ATRACE_CALL();
2092
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002093 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002094 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002095 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002096 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002097 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002098 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002099
Ruben Brunkcc776712015-02-17 20:18:47 -08002100 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2101 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002102
Ruben Brunkcc776712015-02-17 20:18:47 -08002103 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002104 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002105 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002106
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002107 // Transition device state to CLOSED
2108 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2109 String8::format("%d", mCameraId));
2110
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002111 // Notify flashlight that a camera device is closed.
2112 mCameraService->mFlashlight->deviceClosed(
2113 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002114 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002115 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002116 if (mOpsCallback != NULL) {
2117 mAppOpsManager.stopWatchingMode(mOpsCallback);
2118 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002119 mOpsCallback.clear();
2120
2121 return OK;
2122}
2123
2124void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002125 ATRACE_CALL();
2126
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002127 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002128 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002129
2130 if (op != AppOpsManager::OP_CAMERA) {
2131 ALOGW("Unexpected app ops notification received: %d", op);
2132 return;
2133 }
2134
2135 int32_t res;
2136 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002137 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002138 ALOGV("checkOp returns: %d, %s ", res,
2139 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2140 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2141 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2142 "UNKNOWN");
2143
2144 if (res != AppOpsManager::MODE_ALLOWED) {
2145 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2146 myName.string());
2147 // Reset the client PID to allow server-initiated disconnect,
2148 // and to prevent further calls by client.
2149 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002150 CaptureResultExtras resultExtras; // a dummy result (invalid)
2151 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002152 disconnect();
2153 }
2154}
2155
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156// ----------------------------------------------------------------------------
2157
Ruben Brunkcc776712015-02-17 20:18:47 -08002158// Provide client strong pointer for callbacks.
2159sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2160 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2161 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2162 if (clientDescriptor != nullptr) {
2163 return sp<Client>{
2164 static_cast<Client*>(clientDescriptor->getValue().get())};
2165 }
2166 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167}
2168
Jianing Weicb0652e2014-03-12 18:29:36 -07002169void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2170 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002171 (void) errorCode;
2172 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002173 if (mRemoteCallback != NULL) {
2174 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2175 } else {
2176 ALOGE("mRemoteCallback is NULL!!");
2177 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002178}
2179
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002180// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002181void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002182 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002183 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002184}
2185
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002186bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2187 return level == API_1;
2188}
2189
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002190CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2191 mClient(client) {
2192}
2193
2194void CameraService::Client::OpsCallback::opChanged(int32_t op,
2195 const String16& packageName) {
2196 sp<BasicClient> client = mClient.promote();
2197 if (client != NULL) {
2198 client->opChanged(op, packageName);
2199 }
2200}
2201
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002203// CameraState
2204// ----------------------------------------------------------------------------
2205
2206CameraService::CameraState::CameraState(const String8& id, int cost,
2207 const std::set<String8>& conflicting) : mId(id),
2208 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2209
2210CameraService::CameraState::~CameraState() {}
2211
2212ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2213 Mutex::Autolock lock(mStatusLock);
2214 return mStatus;
2215}
2216
2217CameraParameters CameraService::CameraState::getShimParams() const {
2218 return mShimParams;
2219}
2220
2221void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2222 mShimParams = params;
2223}
2224
2225int CameraService::CameraState::getCost() const {
2226 return mCost;
2227}
2228
2229std::set<String8> CameraService::CameraState::getConflicting() const {
2230 return mConflicting;
2231}
2232
2233String8 CameraService::CameraState::getId() const {
2234 return mId;
2235}
2236
2237// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002238// ClientEventListener
2239// ----------------------------------------------------------------------------
2240
2241void CameraService::ClientEventListener::onClientAdded(
2242 const resource_policy::ClientDescriptor<String8,
2243 sp<CameraService::BasicClient>>& descriptor) {
2244 auto basicClient = descriptor.getValue();
2245 if (basicClient.get() != nullptr) {
2246 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2247 notifier.noteStartCamera(descriptor.getKey(),
2248 static_cast<int>(basicClient->getClientUid()));
2249 }
2250}
2251
2252void CameraService::ClientEventListener::onClientRemoved(
2253 const resource_policy::ClientDescriptor<String8,
2254 sp<CameraService::BasicClient>>& descriptor) {
2255 auto basicClient = descriptor.getValue();
2256 if (basicClient.get() != nullptr) {
2257 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2258 notifier.noteStopCamera(descriptor.getKey(),
2259 static_cast<int>(basicClient->getClientUid()));
2260 }
2261}
2262
2263
2264// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002265// CameraClientManager
2266// ----------------------------------------------------------------------------
2267
Ruben Brunk99e69712015-05-26 17:25:07 -07002268CameraService::CameraClientManager::CameraClientManager() {
2269 setListener(std::make_shared<ClientEventListener>());
2270}
2271
Ruben Brunkcc776712015-02-17 20:18:47 -08002272CameraService::CameraClientManager::~CameraClientManager() {}
2273
2274sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2275 const String8& id) const {
2276 auto descriptor = get(id);
2277 if (descriptor == nullptr) {
2278 return sp<BasicClient>{nullptr};
2279 }
2280 return descriptor->getValue();
2281}
2282
2283String8 CameraService::CameraClientManager::toString() const {
2284 auto all = getAll();
2285 String8 ret("[");
2286 bool hasAny = false;
2287 for (auto& i : all) {
2288 hasAny = true;
2289 String8 key = i->getKey();
2290 int32_t cost = i->getCost();
2291 int32_t pid = i->getOwnerId();
2292 int32_t priority = i->getPriority();
2293 auto conflicting = i->getConflicting();
2294 auto clientSp = i->getValue();
2295 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002296 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002297 if (clientSp.get() != nullptr) {
2298 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002299 uid_t clientUid = clientSp->getClientUid();
2300 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002301 }
2302 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2303 PRId32 ", ", key.string(), cost, pid, priority);
2304
Ruben Brunk6267b532015-04-30 17:44:07 -07002305 if (clientSp.get() != nullptr) {
2306 ret.appendFormat("User Id: %d, ", clientUserId);
2307 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002308 if (packageName.size() != 0) {
2309 ret.appendFormat("Client Package Name: %s", packageName.string());
2310 }
2311
2312 ret.append(", Conflicting Client Devices: {");
2313 for (auto& j : conflicting) {
2314 ret.appendFormat("%s, ", j.string());
2315 }
2316 ret.append("})");
2317 }
2318 if (hasAny) ret.append("\n");
2319 ret.append("]\n");
2320 return ret;
2321}
2322
2323CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2324 const String8& key, const sp<BasicClient>& value, int32_t cost,
2325 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2326
2327 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2328 key, value, cost, conflictingKeys, priority, ownerId);
2329}
2330
2331CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2332 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2333 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2334 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2335}
2336
2337// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338
2339static const int kDumpLockRetries = 50;
2340static const int kDumpLockSleep = 60000;
2341
2342static bool tryLock(Mutex& mutex)
2343{
2344 bool locked = false;
2345 for (int i = 0; i < kDumpLockRetries; ++i) {
2346 if (mutex.tryLock() == NO_ERROR) {
2347 locked = true;
2348 break;
2349 }
2350 usleep(kDumpLockSleep);
2351 }
2352 return locked;
2353}
2354
2355status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002356 ATRACE_CALL();
2357
Ruben Brunka8ca9152015-04-07 14:23:40 -07002358 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002360 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 "can't dump CameraService from pid=%d, uid=%d\n",
2362 getCallingPid(),
2363 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 write(fd, result.string(), result.size());
2365 } else {
2366 bool locked = tryLock(mServiceLock);
2367 // failed to lock - CameraService is probably deadlocked
2368 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002369 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002370 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 }
2372
2373 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002374 if (!mModule) {
2375 result = String8::format("No camera module available!\n");
2376 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002377
2378 // Dump event log for error information
2379 dumpEventLog(fd);
2380
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002381 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002382 return NO_ERROR;
2383 }
2384
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002385 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2386 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2387 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2388 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002389 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
Eino-Ville Talvala49c97052016-01-12 14:29:40 -08002390 result.appendFormat("Number of normal camera devices: %d\n", mNumberOfNormalCameras);
Ruben Brunkcc776712015-02-17 20:18:47 -08002391 String8 activeClientString = mActiveClientManager.toString();
2392 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002393 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002394
Ruben Brunkf81648e2014-04-17 16:14:57 -07002395 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2396 if (desc == NULL) {
2397 result.appendFormat("Vendor tags left unimplemented.\n");
2398 } else {
2399 result.appendFormat("Vendor tag definitions:\n");
2400 }
2401
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002402 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002403
2404 if (desc != NULL) {
2405 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2406 }
2407
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002408 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002409
2410 bool stateLocked = tryLock(mCameraStatesLock);
2411 if (!stateLocked) {
2412 result = String8::format("CameraStates in use, may be deadlocked\n");
2413 write(fd, result.string(), result.size());
2414 }
2415
2416 for (auto& state : mCameraStates) {
2417 String8 cameraId = state.first;
2418 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002419 camera_info info;
2420
Ruben Brunkcc776712015-02-17 20:18:47 -08002421 // TODO: Change getCameraInfo + HAL to use String cameraIds
2422 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002423 if (rc != OK) {
2424 result.appendFormat(" Error reading static information!\n");
2425 write(fd, result.string(), result.size());
2426 } else {
2427 result.appendFormat(" Facing: %s\n",
2428 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2429 result.appendFormat(" Orientation: %d\n", info.orientation);
2430 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002431 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002432 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2433 } else {
2434 deviceVersion = info.device_version;
2435 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002436
2437 auto conflicting = state.second->getConflicting();
2438 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2439 result.appendFormat(" Conflicting Devices:");
2440 for (auto& id : conflicting) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002441 result.appendFormat(" %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002442 }
2443 if (conflicting.size() == 0) {
2444 result.appendFormat(" NONE");
2445 }
2446 result.appendFormat("\n");
2447
2448 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002449 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002450 result.appendFormat(" Device static metadata:\n");
2451 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002452 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002453 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002454 } else {
2455 write(fd, result.string(), result.size());
2456 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002457
2458 CameraParameters p = state.second->getShimParams();
2459 if (!p.isEmpty()) {
2460 result = String8::format(" Camera1 API shim is using parameters:\n ");
2461 write(fd, result.string(), result.size());
2462 p.dump(fd, args);
2463 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002464 }
2465
Ruben Brunkcc776712015-02-17 20:18:47 -08002466 auto clientDescriptor = mActiveClientManager.get(cameraId);
2467 if (clientDescriptor == nullptr) {
2468 result = String8::format(" Device %s is closed, no client instance\n",
2469 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002470 write(fd, result.string(), result.size());
2471 continue;
2472 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002474 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2475 cameraId.string());
2476 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2477 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2478
2479 auto client = clientDescriptor->getValue();
2480 result.appendFormat("Client package: %s\n",
2481 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002482 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002483
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002484 client->dumpClient(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002486
2487 if (stateLocked) mCameraStatesLock.unlock();
2488
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002490 result = String8::format("\nNo active camera clients yet.\n");
2491 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 }
2493
2494 if (locked) mServiceLock.unlock();
2495
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002496 // Dump camera traces if there were any
2497 write(fd, "\n", 1);
2498 camera3::CameraTraces::dump(fd, args);
2499
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 // change logging level
2501 int n = args.size();
2502 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002503 String16 verboseOption("-v");
2504 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 String8 levelStr(args[i+1]);
2506 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002507 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002509 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 }
2511 }
2512 }
2513 return NO_ERROR;
2514}
2515
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002516void CameraService::dumpEventLog(int fd) {
2517 String8 result = String8("\nPrior client events (most recent at top):\n");
2518
2519 Mutex::Autolock l(mLogLock);
2520 for (const auto& msg : mEventLog) {
2521 result.appendFormat(" %s\n", msg.string());
2522 }
2523
2524 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2525 result.append(" ...\n");
2526 } else if (mEventLog.size() == 0) {
2527 result.append(" [no events yet]\n");
2528 }
2529 result.append("\n");
2530
2531 write(fd, result.string(), result.size());
2532}
2533
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002534void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002535 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002536 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2537 if (mTorchClientMap[i] == who) {
2538 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002539 String8 cameraId = mTorchClientMap.keyAt(i);
2540 status_t res = mFlashlight->setTorchMode(cameraId, false);
2541 if (res) {
2542 ALOGE("%s: torch client died but couldn't turn off torch: "
2543 "%s (%d)", __FUNCTION__, strerror(-res), res);
2544 return;
2545 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002546 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002547 break;
2548 }
2549 }
2550}
2551
Ruben Brunkcc776712015-02-17 20:18:47 -08002552/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002553
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002554 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002555 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2556 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002557 */
2558
Ruben Brunka8ca9152015-04-07 14:23:40 -07002559 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2560
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002561 // check torch client
2562 handleTorchClientBinderDied(who);
2563
2564 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002565 if(!evictClientIdByRemote(who)) {
2566 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002567 return;
2568 }
2569
Ruben Brunkcc776712015-02-17 20:18:47 -08002570 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2571 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002572}
2573
Ruben Brunkcc776712015-02-17 20:18:47 -08002574void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2575 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002576}
2577
Ruben Brunkcc776712015-02-17 20:18:47 -08002578void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2579 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2580 // Do not lock mServiceLock here or can get into a deadlock from
2581 // connect() -> disconnect -> updateStatus
2582
2583 auto state = getCameraState(cameraId);
2584
2585 if (state == nullptr) {
2586 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2587 cameraId.string());
2588 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002589 }
2590
Ruben Brunkcc776712015-02-17 20:18:47 -08002591 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2592 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2593 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2594 (const String8& cameraId, ICameraServiceListener::Status status) {
2595
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002596 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2597 // Update torch status if it has a flash unit.
2598 Mutex::Autolock al(mTorchStatusMutex);
2599 ICameraServiceListener::TorchStatus torchStatus;
2600 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2601 NAME_NOT_FOUND) {
2602 ICameraServiceListener::TorchStatus newTorchStatus =
2603 status == ICameraServiceListener::STATUS_PRESENT ?
2604 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2605 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2606 if (torchStatus != newTorchStatus) {
2607 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2608 }
2609 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002610 }
2611
2612 Mutex::Autolock lock(mStatusListenerLock);
2613
2614 for (auto& listener : mListenerList) {
2615 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2616 int id = cameraIdToInt(cameraId);
2617 if (id != -1) listener->onStatusChanged(status, id);
2618 }
2619 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002620}
2621
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002622void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2623 const String8& cameraId) {
2624 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2625 if (proxyBinder == nullptr) return;
2626 String16 id(cameraId);
2627 proxyBinder->notifyCameraState(id, newState);
2628}
2629
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002630status_t CameraService::getTorchStatusLocked(
2631 const String8& cameraId,
2632 ICameraServiceListener::TorchStatus *status) const {
2633 if (!status) {
2634 return BAD_VALUE;
2635 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002636 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2637 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002638 // invalid camera ID or the camera doesn't have a flash unit
2639 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002640 }
2641
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002642 *status = mTorchStatusMap.valueAt(index);
2643 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002644}
2645
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002646status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002647 ICameraServiceListener::TorchStatus status) {
2648 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2649 if (index == NAME_NOT_FOUND) {
2650 return BAD_VALUE;
2651 }
2652 ICameraServiceListener::TorchStatus& item =
2653 mTorchStatusMap.editValueAt(index);
2654 item = status;
2655
2656 return OK;
2657}
2658
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659}; // namespace android