blob: 6124fedde299e3e9112a56c7c59f479e6abb888b [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 Talvalad56db1d2015-12-17 16:50:35 -080031#include <android/hardware/ICamera.h>
32#include <android/hardware/ICameraClient.h>
33
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080034#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/IPCThreadState.h>
36#include <binder/IServiceManager.h>
37#include <binder/MemoryBase.h>
38#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080039#include <binder/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070041#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080042#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <hardware/hardware.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070044#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080046#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070048#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <utils/Errors.h>
50#include <utils/Log.h>
51#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080052#include <utils/Trace.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080053#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080054#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070055#include <system/camera_metadata.h>
56#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
58#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070059#include "api1/CameraClient.h"
60#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070061#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070062#include "utils/CameraTraces.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070063
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080064namespace {
65 const char* kPermissionServiceName = "permission";
66}; // namespace anonymous
67
Mathias Agopian65ab4712010-07-14 17:59:35 -070068namespace android {
69
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080070using binder::Status;
71using namespace hardware;
72
Mathias Agopian65ab4712010-07-14 17:59:35 -070073// ----------------------------------------------------------------------------
74// Logging support -- this is for debugging only
75// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070076volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
Steve Blockb8a80522011-12-20 16:23:08 +000078#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
79#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
81static void setLogLevel(int level) {
82 android_atomic_write(level, &gLogLevel);
83}
84
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080085// Convenience methods for constructing binder::Status objects for error returns
86
87#define STATUS_ERROR(errorCode, errorString) \
88 binder::Status::fromServiceSpecificError(errorCode, \
89 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
90
91#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
92 binder::Status::fromServiceSpecificError(errorCode, \
93 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
94 __VA_ARGS__))
95
Mathias Agopian65ab4712010-07-14 17:59:35 -070096// ----------------------------------------------------------------------------
97
Igor Murashkincba2c162013-03-20 15:56:31 -070098extern "C" {
99static void camera_device_status_change(
100 const struct camera_module_callbacks* callbacks,
101 int camera_id,
102 int new_status) {
103 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -0800104 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -0700105
Ruben Brunkcc776712015-02-17 20:18:47 -0800106 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
107 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -0700108}
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800109
110static void torch_mode_status_change(
111 const struct camera_module_callbacks* callbacks,
112 const char* camera_id,
113 int new_status) {
114 if (!callbacks || !camera_id) {
115 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
116 callbacks, camera_id);
117 }
118 sp<CameraService> cs = const_cast<CameraService*>(
119 static_cast<const CameraService*>(callbacks));
120
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800121 int32_t status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800122 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800123 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800124 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
125 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800126 case TORCH_MODE_STATUS_AVAILABLE_OFF:
127 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
128 break;
129 case TORCH_MODE_STATUS_AVAILABLE_ON:
130 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800131 break;
132 default:
133 ALOGE("Unknown torch status %d", new_status);
134 return;
135 }
136
137 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800138 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800139 status);
140}
Igor Murashkincba2c162013-03-20 15:56:31 -0700141} // extern "C"
142
Mathias Agopian65ab4712010-07-14 17:59:35 -0700143// ----------------------------------------------------------------------------
144
145// This is ugly and only safe if we never re-create the CameraService, but
146// should be ok for now.
147static CameraService *gCameraService;
148
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800149CameraService::CameraService() :
150 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800151 mNumberOfCameras(0), mNumberOfNormalCameras(0),
152 mSoundRef(0), mModule(nullptr) {
Steve Blockdf64d152012-01-04 20:05:49 +0000153 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700154 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800155
Igor Murashkincba2c162013-03-20 15:56:31 -0700156 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800157 this->torch_mode_status_change = android::torch_mode_status_change;
158
Ruben Brunkcc776712015-02-17 20:18:47 -0800159 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700160}
161
Iliyan Malchev8951a972011-04-14 16:55:59 -0700162void CameraService::onFirstRef()
163{
Ruben Brunkcc776712015-02-17 20:18:47 -0800164 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800165
Iliyan Malchev8951a972011-04-14 16:55:59 -0700166 BnCameraService::onFirstRef();
167
Ruben Brunk99e69712015-05-26 17:25:07 -0700168 // Update battery life tracking if service is restarting
169 BatteryNotifier& notifier(BatteryNotifier::getInstance());
170 notifier.noteResetCamera();
171 notifier.noteResetFlashlight();
172
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800173 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700174 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
175 (const hw_module_t **)&rawModule);
176 if (err < 0) {
177 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
178 logServiceError("Could not load camera HAL module", err);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700179 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700180 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800181
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700182 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700183 err = mModule->init();
184 if (err != OK) {
185 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
186 strerror(-err));
187 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800188
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700189 delete mModule;
190 mModule = nullptr;
191 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700192 }
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700193 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700194
195 mNumberOfCameras = mModule->getNumberOfCameras();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700196 mNumberOfNormalCameras = mNumberOfCameras;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700197
Yin-Chia Yehd4a653a2015-10-14 11:05:44 -0700198 // Setup vendor tags before we call get_camera_info the first time
199 // because HAL might need to setup static vendor keys in get_camera_info
200 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
201 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
202 setUpVendorTags();
203 }
204
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700205 mFlashlight = new CameraFlashlight(*mModule, *this);
206 status_t res = mFlashlight->findFlashUnits();
207 if (res) {
208 // impossible because we haven't open any camera devices.
209 ALOGE("Failed to find flash units.");
210 }
211
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700212 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700213 for (int i = 0; i < mNumberOfCameras; i++) {
214 String8 cameraId = String8::format("%d", i);
215
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700216 // Get camera info
217
218 struct camera_info info;
219 bool haveInfo = true;
220 status_t rc = mModule->getCameraInfo(i, &info);
221 if (rc != NO_ERROR) {
222 ALOGE("%s: Received error loading camera info for device %d, cost and"
223 " conflicting devices fields set to defaults for this device.",
224 __FUNCTION__, i);
225 haveInfo = false;
226 }
227
228 // Check for backwards-compatibility support
229 if (haveInfo) {
230 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
231 delete mModule;
232 mModule = nullptr;
233 return;
234 }
235 }
236
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700237 // Defaults to use for cost and conflicting devices
238 int cost = 100;
239 char** conflicting_devices = nullptr;
240 size_t conflicting_devices_length = 0;
241
242 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700243 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
244 cost = info.resource_cost;
245 conflicting_devices = info.conflicting_devices;
246 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700247 }
248
249 std::set<String8> conflicting;
250 for (size_t i = 0; i < conflicting_devices_length; i++) {
251 conflicting.emplace(String8(conflicting_devices[i]));
252 }
253
254 // Initialize state for each camera device
255 {
256 Mutex::Autolock lock(mCameraStatesLock);
257 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
258 conflicting));
259 }
260
261 if (mFlashlight->hasFlashUnit(cameraId)) {
262 mTorchStatusMap.add(cameraId,
263 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
264 }
265 }
266
267 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
268 mModule->setCallbacks(this);
269 }
270
Ruben Brunk2823ce02015-05-19 17:25:13 -0700271 CameraService::pingCameraServiceProxy();
272}
273
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700274sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Ruben Brunk2823ce02015-05-19 17:25:13 -0700275 sp<IServiceManager> sm = defaultServiceManager();
276 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
277 if (binder == nullptr) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700278 return nullptr;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700279 }
280 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700281 return proxyBinder;
282}
283
284void CameraService::pingCameraServiceProxy() {
285 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
286 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700287 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700288}
289
Mathias Agopian65ab4712010-07-14 17:59:35 -0700290CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800291 if (mModule) {
292 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800293 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800294 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800295 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800296 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700297}
298
Ruben Brunkcc776712015-02-17 20:18:47 -0800299void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
300 camera_device_status_t newStatus) {
301 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700302 cameraId, newStatus);
303
Ruben Brunkcc776712015-02-17 20:18:47 -0800304 String8 id = String8::format("%d", cameraId);
305 std::shared_ptr<CameraState> state = getCameraState(id);
306
307 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700308 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
309 return;
310 }
311
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800312 int32_t oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800313
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800314 if (oldStatus == static_cast<int32_t>(newStatus)) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800315 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700316 return;
317 }
318
Igor Murashkincba2c162013-03-20 15:56:31 -0700319 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700320 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
321 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800322 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700323 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800324 // Don't do this in updateStatus to avoid deadlock over mServiceLock
325 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700326
Ruben Brunkcc776712015-02-17 20:18:47 -0800327 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
328 // to this device until the status changes
329 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700330
Ruben Brunkcc776712015-02-17 20:18:47 -0800331 // Remove cached shim parameters
332 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700333
Ruben Brunkcc776712015-02-17 20:18:47 -0800334 // Remove the client from the list of active clients
335 clientToDisconnect = removeClientLocked(id);
336
337 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800338 clientToDisconnect->notifyError(
339 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800340 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700341 }
342
Ruben Brunkcc776712015-02-17 20:18:47 -0800343 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
344 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700345
Ruben Brunkcc776712015-02-17 20:18:47 -0800346 // Disconnect client
347 if (clientToDisconnect.get() != nullptr) {
348 // Ensure not in binder RPC so client disconnect PID checks work correctly
349 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
350 "onDeviceStatusChanged must be called from the camera service process!");
351 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700352 }
353
Ruben Brunkcc776712015-02-17 20:18:47 -0800354 } else {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800355 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700356 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
357 newStatus));
358 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800359 updateStatus(static_cast<int32_t>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700360 }
361
Igor Murashkincba2c162013-03-20 15:56:31 -0700362}
363
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800364void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800365 int32_t newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800366 Mutex::Autolock al(mTorchStatusMutex);
367 onTorchStatusChangedLocked(cameraId, newStatus);
368}
369
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800370void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800371 int32_t newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800372 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
373 __FUNCTION__, cameraId.string(), newStatus);
374
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800375 int32_t status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800376 status_t res = getTorchStatusLocked(cameraId, &status);
377 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700378 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
379 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800380 return;
381 }
382 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800383 return;
384 }
385
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800386 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800387 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800388 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
389 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800390 return;
391 }
392
Ruben Brunkcc776712015-02-17 20:18:47 -0800393 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700394 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700395 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700396 auto iter = mTorchUidMap.find(cameraId);
397 if (iter != mTorchUidMap.end()) {
398 int oldUid = iter->second.second;
399 int newUid = iter->second.first;
400 BatteryNotifier& notifier(BatteryNotifier::getInstance());
401 if (oldUid != newUid) {
402 // If the UID has changed, log the status and update current UID in mTorchUidMap
403 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
404 notifier.noteFlashlightOff(cameraId, oldUid);
405 }
406 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
407 notifier.noteFlashlightOn(cameraId, newUid);
408 }
409 iter->second.second = newUid;
410 } else {
411 // If the UID has not changed, log the status
412 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
413 notifier.noteFlashlightOn(cameraId, oldUid);
414 } else {
415 notifier.noteFlashlightOff(cameraId, oldUid);
416 }
417 }
418 }
419 }
420
421 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800422 Mutex::Autolock lock(mStatusListenerLock);
423 for (auto& i : mListenerList) {
424 i->onTorchStatusChanged(newStatus, String16{cameraId});
425 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800426 }
427}
428
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800429Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700430 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700431 switch (type) {
432 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800433 *numCameras = mNumberOfNormalCameras;
434 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700435 case CAMERA_TYPE_ALL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800436 *numCameras = mNumberOfCameras;
437 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700438 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800439 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700440 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800441 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
442 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700443 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800444 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445}
446
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800447Status CameraService::getCameraInfo(int cameraId,
448 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700449 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700450 if (!mModule) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800451 return STATUS_ERROR(ERROR_DISCONNECTED,
452 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700453 }
454
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800456 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
457 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458 }
459
Iliyan Malchev8951a972011-04-14 16:55:59 -0700460 struct camera_info info;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800461 Status rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800462 mModule->getCameraInfo(cameraId, &info));
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800463
464 if (rc.isOk()) {
465 cameraInfo->facing = info.facing;
466 cameraInfo->orientation = info.orientation;
Yin-Chia Yeh9b5a6e92016-04-22 13:24:05 -0700467 // CameraInfo is for android.hardware.Camera which does not
468 // support external camera facing. The closest approximation would be
469 // front camera.
Yin-Chia Yeh13cd59a2016-11-29 12:13:15 -0800470 if (cameraInfo->facing == CAMERA_FACING_EXTERNAL) {
471 cameraInfo->facing = CAMERA_FACING_FRONT;
Yin-Chia Yeh9b5a6e92016-04-22 13:24:05 -0700472 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800473 }
Iliyan Malchev8951a972011-04-14 16:55:59 -0700474 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475}
476
Ruben Brunkcc776712015-02-17 20:18:47 -0800477int CameraService::cameraIdToInt(const String8& cameraId) {
478 errno = 0;
479 size_t pos = 0;
480 int ret = stoi(std::string{cameraId.string()}, &pos);
481 if (errno != 0 || pos != cameraId.size()) {
482 return -1;
483 }
484 return ret;
485}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700486
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800487Status CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700488 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800489
490 Status ret = Status::ok();
491
Ruben Brunkb2119af2014-05-09 19:57:56 -0700492 struct CameraInfo info;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800493 if (!(ret = getCameraInfo(cameraId, &info)).isOk()) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700494 return ret;
495 }
496
497 CameraMetadata shimInfo;
498 int32_t orientation = static_cast<int32_t>(info.orientation);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800499 status_t rc;
500 if ((rc = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
501 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
502 "Error updating metadata: %d (%s)", rc, strerror(-rc));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700503 }
504
505 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
506 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800507 if ((rc = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
508 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
509 "Error updating metadata: %d (%s)", rc, strerror(-rc));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700510 }
511
Igor Murashkin65d14b92014-06-17 12:03:20 -0700512 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800513 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -0700514 // Error logged by callee
515 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700516 }
517
518 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700519 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700520 Vector<int32_t> formats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700521 {
522 shimParams.getSupportedPreviewSizes(/*out*/sizes);
523 shimParams.getSupportedPreviewFormats(/*out*/formats);
524 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700525 }
526
527 // Always include IMPLEMENTATION_DEFINED
528 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
529
530 const size_t INTS_PER_CONFIG = 4;
531
532 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700533 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
534
535 Vector<int32_t> streamConfigs;
536 streamConfigs.setCapacity(streamConfigSize);
537
Ruben Brunkb2119af2014-05-09 19:57:56 -0700538 for (size_t i = 0; i < formats.size(); ++i) {
539 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700540 streamConfigs.add(formats[i]);
541 streamConfigs.add(sizes[j].width);
542 streamConfigs.add(sizes[j].height);
543 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700544 }
545 }
546
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700547 for (size_t i = 0; i < jpegSizes.size(); ++i) {
548 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
549 streamConfigs.add(jpegSizes[i].width);
550 streamConfigs.add(jpegSizes[i].height);
551 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
552 }
553
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800554 if ((rc = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700555 streamConfigs.array(), streamConfigSize)) != OK) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800556 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
557 "Error updating metadata: %d (%s)", rc, strerror(-rc));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700558 }
559
560 int64_t fakeMinFrames[0];
561 // TODO: Fixme, don't fake min frame durations.
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800562 if ((rc = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
Ruben Brunkb2119af2014-05-09 19:57:56 -0700563 fakeMinFrames, 0)) != OK) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800564 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
565 "Error updating metadata: %d (%s)", rc, strerror(-rc));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700566 }
567
568 int64_t fakeStalls[0];
569 // TODO: Fixme, don't fake stall durations.
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800570 if ((rc = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
Ruben Brunkb2119af2014-05-09 19:57:56 -0700571 fakeStalls, 0)) != OK) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800572 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
573 "Error updating metadata: %d (%s)", rc, strerror(-rc));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700574 }
575
576 *cameraInfo = shimInfo;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700578}
579
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580Status CameraService::getCameraCharacteristics(int cameraId,
Zhijun He2b59be82013-09-25 10:14:30 -0700581 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700582 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700583 if (!cameraInfo) {
584 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800585 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700586 }
587
588 if (!mModule) {
589 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800590 return STATUS_ERROR(ERROR_DISCONNECTED,
591 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700592 }
593
Zhijun He2b59be82013-09-25 10:14:30 -0700594 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
595 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800596 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
597 "Invalid camera id: %d", cameraId);
Zhijun He2b59be82013-09-25 10:14:30 -0700598 }
599
600 int facing;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800601 Status ret;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800602 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800603 getDeviceVersion(cameraId, &facing) < CAMERA_DEVICE_API_VERSION_3_0) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700604 /**
605 * Backwards compatibility mode for old HALs:
606 * - Convert CameraInfo into static CameraMetadata properties.
607 * - Retrieve cached CameraParameters for this camera. If none exist,
608 * attempt to open CameraClient and retrieve the CameraParameters.
609 * - Convert cached CameraParameters into static CameraMetadata
610 * properties.
611 */
612 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700613
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800614 ret = generateShimMetadata(cameraId, cameraInfo);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700615 } else {
616 /**
617 * Normal HAL 2.1+ codepath.
618 */
619 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800620 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800621 if (ret.isOk()) {
622 *cameraInfo = info.static_camera_characteristics;
623 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700624 }
Zhijun He2b59be82013-09-25 10:14:30 -0700625
626 return ret;
627}
628
Ruben Brunkcc776712015-02-17 20:18:47 -0800629int CameraService::getCallingPid() {
630 return IPCThreadState::self()->getCallingPid();
631}
632
633int CameraService::getCallingUid() {
634 return IPCThreadState::self()->getCallingUid();
635}
636
637String8 CameraService::getFormattedCurrentTime() {
638 time_t now = time(nullptr);
639 char formattedTime[64];
640 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
641 return String8(formattedTime);
642}
643
644int CameraService::getCameraPriorityFromProcState(int procState) {
645 // Find the priority for the camera usage based on the process state. Higher priority clients
646 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700647 if (procState < 0) {
648 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
649 procState);
650 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800651 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700652 // Treat sleeping TOP processes the same as regular TOP processes, for
653 // access priority. This is important for lock-screen camera launch scenarios
654 if (procState == PROCESS_STATE_TOP_SLEEPING) {
655 procState = PROCESS_STATE_TOP;
656 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700657 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800658}
659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800660Status CameraService::getCameraVendorTagDescriptor(
661 /*out*/
662 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700663 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800664 if (!mModule) {
665 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800666 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800667 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800668 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
669 if (globalDescriptor != nullptr) {
670 *desc = *(globalDescriptor.get());
671 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800672 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800673}
674
Igor Murashkin634a5152013-02-20 17:15:11 -0800675int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700676 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800677 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800678 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800679 return -1;
680 }
681
682 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800683 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800684 deviceVersion = info.device_version;
685 } else {
686 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
687 }
688
689 if (facing) {
690 *facing = info.facing;
691 }
692
693 return deviceVersion;
694}
695
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800696Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700697 switch(err) {
698 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800699 return Status::ok();
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700700 case -EINVAL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800701 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
702 "CameraId is not valid for HAL module");
703 case -ENODEV:
704 return STATUS_ERROR(ERROR_DISCONNECTED,
705 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700706 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800707 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
708 "Camera HAL encountered error %d: %s",
709 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700710 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800711}
712
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800713bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700714 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800715 vendor_tag_ops_t vOps = vendor_tag_ops_t();
716
717 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800718 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800719 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
720 return false;
721 }
722
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800723 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800724
725 // Ensure all vendor operations are present
726 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
727 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
728 vOps.get_tag_type == NULL) {
729 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
730 , __FUNCTION__);
731 return false;
732 }
733
734 // Read all vendor tag definitions into a descriptor
735 sp<VendorTagDescriptor> desc;
736 status_t res;
737 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
738 != OK) {
739 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
740 "received error %s (%d). Camera clients will not be able to use"
741 "vendor tags", __FUNCTION__, strerror(res), res);
742 return false;
743 }
744
745 // Set the global descriptor to use with camera metadata
746 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
747 return true;
748}
749
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800750Status CameraService::makeClient(const sp<CameraService>& cameraService,
751 const sp<IInterface>& cameraCb, const String16& packageName, int cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800752 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
753 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
754 /*out*/sp<BasicClient>* client) {
755
Ruben Brunkcc776712015-02-17 20:18:47 -0800756 if (halVersion < 0 || halVersion == deviceVersion) {
757 // Default path: HAL version is unspecified by caller, create CameraClient
758 // based on device version reported by the HAL.
759 switch(deviceVersion) {
760 case CAMERA_DEVICE_API_VERSION_1_0:
761 if (effectiveApiLevel == API_1) { // Camera1 API route
762 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800763 *client = new CameraClient(cameraService, tmp, packageName, cameraId, facing,
Ruben Brunkcc776712015-02-17 20:18:47 -0800764 clientPid, clientUid, getpid(), legacyMode);
765 } else { // Camera2 API route
766 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800767 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
768 "Camera device \"%d\" HAL version %d does not support camera2 API",
769 cameraId, deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800770 }
771 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800772 case CAMERA_DEVICE_API_VERSION_3_0:
773 case CAMERA_DEVICE_API_VERSION_3_1:
774 case CAMERA_DEVICE_API_VERSION_3_2:
775 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700776 case CAMERA_DEVICE_API_VERSION_3_4:
Ruben Brunkcc776712015-02-17 20:18:47 -0800777 if (effectiveApiLevel == API_1) { // Camera1 API route
778 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 *client = new Camera2Client(cameraService, tmp, packageName, cameraId, facing,
Ruben Brunkcc776712015-02-17 20:18:47 -0800780 clientPid, clientUid, servicePid, legacyMode);
781 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800782 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
783 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
784 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800785 facing, clientPid, clientUid, servicePid);
786 }
787 break;
788 default:
789 // Should not be reachable
790 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800791 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
792 "Camera device \"%d\" has unknown HAL version %d",
793 cameraId, deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800794 }
795 } else {
796 // A particular HAL version is requested by caller. Create CameraClient
797 // based on the requested HAL version.
798 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
799 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
800 // Only support higher HAL version device opened as HAL1.0 device.
801 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800802 *client = new CameraClient(cameraService, tmp, packageName, cameraId, facing,
Ruben Brunkcc776712015-02-17 20:18:47 -0800803 clientPid, clientUid, servicePid, legacyMode);
804 } else {
805 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
806 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
807 " opened as HAL %x device", halVersion, deviceVersion,
808 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800809 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
810 "Camera device \"%d\" (HAL version %d) cannot be opened as HAL version %d",
811 cameraId, deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800812 }
813 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800815}
816
Ruben Brunk6267b532015-04-30 17:44:07 -0700817String8 CameraService::toString(std::set<userid_t> intSet) {
818 String8 s("");
819 bool first = true;
820 for (userid_t i : intSet) {
821 if (first) {
822 s.appendFormat("%d", i);
823 first = false;
824 } else {
825 s.appendFormat(", %d", i);
826 }
827 }
828 return s;
829}
830
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831Status CameraService::initializeShimMetadata(int cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700833
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800834 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800835 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800838 if (!(ret = connectHelper<ICameraClient,Client>(
839 sp<ICameraClient>{nullptr}, id, static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
840 internalPackageName, uid, USE_CALLING_PID,
841 API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
842 /*out*/ tmp)
843 ).isOk()) {
844 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700845 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800846 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700847}
848
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800849Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700850 /*out*/
851 CameraParameters* parameters) {
852
853 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
854
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800855 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700856
857 if (parameters == NULL) {
858 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800859 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700860 }
861
Ruben Brunkcc776712015-02-17 20:18:47 -0800862 String8 id = String8::format("%d", cameraId);
863
864 // Check if we already have parameters
865 {
866 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700867 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800868 auto cameraState = getCameraState(id);
869 if (cameraState == nullptr) {
870 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800871 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
872 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800873 }
874 CameraParameters p = cameraState->getShimParams();
875 if (!p.isEmpty()) {
876 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800877 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700878 }
879 }
880
Ruben Brunkcc776712015-02-17 20:18:47 -0800881 int64_t token = IPCThreadState::self()->clearCallingIdentity();
882 ret = initializeShimMetadata(cameraId);
883 IPCThreadState::self()->restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800884 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800885 // Error already logged by callee
886 return ret;
887 }
888
889 // Check for parameters again
890 {
891 // Scope for service lock
892 Mutex::Autolock lock(mServiceLock);
893 auto cameraState = getCameraState(id);
894 if (cameraState == nullptr) {
895 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800896 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
897 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700898 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800899 CameraParameters p = cameraState->getShimParams();
900 if (!p.isEmpty()) {
901 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800902 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700903 }
904 }
905
Ruben Brunkcc776712015-02-17 20:18:47 -0800906 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
907 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800908 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700909}
910
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800911// Can camera service trust the caller based on the calling UID?
912static bool isTrustedCallingUid(uid_t uid) {
913 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700914 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800915 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700916 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800917 return true;
918 default:
919 return false;
920 }
921}
922
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800923Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700924 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
925 /*out*/int& originalClientPid) const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800926
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 int callingPid = getCallingPid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800928 int callingUid = getCallingUid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500929
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800930 // Check if we can trust clientUid
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800931 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800932 clientUid = callingUid;
933 } else if (!isTrustedCallingUid(callingUid)) {
934 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
935 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800936 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
937 "Untrusted caller (calling PID %d, UID %d) trying to "
938 "forward camera access to camera %s for client %s (PID %d, UID %d)",
939 callingPid, callingUid, cameraId.string(),
940 clientName8.string(), clientUid, clientPid);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800941 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800943 // Check if we can trust clientPid
944 if (clientPid == USE_CALLING_PID) {
945 clientPid = callingPid;
946 } else if (!isTrustedCallingUid(callingUid)) {
947 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
948 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800949 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
950 "Untrusted caller (calling PID %d, UID %d) trying to "
951 "forward camera access to camera %s for client %s (PID %d, UID %d)",
952 callingPid, callingUid, cameraId.string(),
953 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800954 }
955
956 // If it's not calling from cameraserver, check the permission.
957 if (callingPid != getpid() &&
958 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
959 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800960 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
961 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
962 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800963 }
964
965 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
966 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700967 originalClientPid = clientPid;
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800968 clientPid = callingPid;
969
Iliyan Malchev8951a972011-04-14 16:55:59 -0700970 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800971 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
972 callingPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800973 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
974 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700975 }
976
Ruben Brunkcc776712015-02-17 20:18:47 -0800977 if (getCameraState(cameraId) == nullptr) {
978 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
979 cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800980 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
981 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 }
983
Ruben Brunk6267b532015-04-30 17:44:07 -0700984 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800985
Ruben Brunka8ca9152015-04-07 14:23:40 -0700986 // Only allow clients who are being used by the current foreground device user, unless calling
987 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700988 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
989 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
990 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
991 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800992 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
993 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
994 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700995 }
996
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800997 status_t err = checkIfDeviceIsUsable(cameraId);
998 if (err != NO_ERROR) {
999 switch(err) {
1000 case -ENODEV:
1001 case -EBUSY:
1002 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1003 "No camera device with ID \"%s\" currently available", cameraId.string());
1004 default:
1005 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1006 "Unknown error connecting to ID \"%s\"", cameraId.string());
1007 }
1008 }
1009 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001010}
1011
1012status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1013 auto cameraState = getCameraState(cameraId);
1014 int callingPid = getCallingPid();
1015 if (cameraState == nullptr) {
1016 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1017 cameraId.string());
1018 return -ENODEV;
1019 }
1020
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001021 int32_t currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -07001022 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001023 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1024 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001025 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -07001026 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001027 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1028 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001029 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001030 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001031
Ruben Brunkcc776712015-02-17 20:18:47 -08001032 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001033}
1034
Ruben Brunkcc776712015-02-17 20:18:47 -08001035void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1036 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001037
Ruben Brunkcc776712015-02-17 20:18:47 -08001038 // Make a descriptor for the incoming client
1039 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1040 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1041
1042 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1043 String8(client->getPackageName()));
1044
1045 if (evicted.size() > 0) {
1046 // This should never happen - clients should already have been removed in disconnect
1047 for (auto& i : evicted) {
1048 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1049 __FUNCTION__, i->getKey().string());
1050 }
1051
1052 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1053 __FUNCTION__);
1054 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001055
1056 // And register a death notification for the client callback. Do
1057 // this last to avoid Binder policy where a nested Binder
1058 // transaction might be pre-empted to service the client death
1059 // notification if the client process dies before linkToDeath is
1060 // invoked.
1061 sp<IBinder> remoteCallback = client->getRemote();
1062 if (remoteCallback != nullptr) {
1063 remoteCallback->linkToDeath(this);
1064 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001065}
1066
1067status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1068 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1069 /*out*/
1070 sp<BasicClient>* client,
1071 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001072 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001073 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001074 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001075 DescriptorPtr clientDescriptor;
1076 {
1077 if (effectiveApiLevel == API_1) {
1078 // If we are using API1, any existing client for this camera ID with the same remote
1079 // should be returned rather than evicted to allow MediaRecorder to work properly.
1080
1081 auto current = mActiveClientManager.get(cameraId);
1082 if (current != nullptr) {
1083 auto clientSp = current->getValue();
1084 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001085 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1086 ALOGW("CameraService connect called from same client, but with a different"
1087 " API level, evicting prior client...");
1088 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001089 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001090 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001091 *client = clientSp;
1092 return NO_ERROR;
1093 }
1094 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001095 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001096 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001097
Ruben Brunkcc776712015-02-17 20:18:47 -08001098 // Get current active client PIDs
1099 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1100 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001101
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001102 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1103 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1104 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1105 // not have an out-of-class definition.
1106 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001107
Ruben Brunkcc776712015-02-17 20:18:47 -08001108 // Get priorites of all active PIDs
1109 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1110 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001111
Ruben Brunkcc776712015-02-17 20:18:47 -08001112 // Update all active clients' priorities
1113 std::map<int,int> pidToPriorityMap;
1114 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1115 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1116 }
1117 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001118
Ruben Brunkcc776712015-02-17 20:18:47 -08001119 // Get state for the given cameraId
1120 auto state = getCameraState(cameraId);
1121 if (state == nullptr) {
1122 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1123 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001124 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001125 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001126 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001127
1128 // Make descriptor for incoming client
1129 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1130 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1131 state->getConflicting(),
1132 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1133
1134 // Find clients that would be evicted
1135 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1136
1137 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1138 // background, so we cannot do evictions
1139 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1140 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1141 " priority).", clientPid);
1142
1143 sp<BasicClient> clientSp = clientDescriptor->getValue();
1144 String8 curTime = getFormattedCurrentTime();
1145 auto incompatibleClients =
1146 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1147
1148 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001149 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 cameraId.string(), packageName.string(), clientPid,
1151 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1152
1153 for (auto& i : incompatibleClients) {
1154 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1155 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1156 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1157 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001158 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1159 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1160 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1161 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001162 }
1163
1164 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001165 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001166 mEventLog.add(msg);
1167
1168 return -EBUSY;
1169 }
1170
1171 for (auto& i : evicted) {
1172 sp<BasicClient> clientSp = i->getValue();
1173 if (clientSp.get() == nullptr) {
1174 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1175
1176 // TODO: Remove this
1177 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1178 __FUNCTION__);
1179 mActiveClientManager.remove(i);
1180 continue;
1181 }
1182
1183 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1184 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001185 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001186
Ruben Brunkcc776712015-02-17 20:18:47 -08001187 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001188 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1189 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1190 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001191 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1192 i->getOwnerId(), i->getPriority(), cameraId.string(),
1193 packageName.string(), clientPid,
1194 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1195
1196 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001197 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001198 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001199 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001200 }
1201
Ruben Brunkcc776712015-02-17 20:18:47 -08001202 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1203 // other clients from connecting in mServiceLockWrapper if held
1204 mServiceLock.unlock();
1205
1206 // Clear caller identity temporarily so client disconnect PID checks work correctly
1207 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1208
1209 // Destroy evicted clients
1210 for (auto& i : evictedClients) {
1211 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001212 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001213 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001214
1215 IPCThreadState::self()->restoreCallingIdentity(token);
1216
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001217 for (const auto& i : evictedClients) {
1218 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1219 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1220 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1221 if (ret == TIMED_OUT) {
1222 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1223 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1224 mActiveClientManager.toString().string());
1225 return -EBUSY;
1226 }
1227 if (ret != NO_ERROR) {
1228 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1229 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1230 ret, mActiveClientManager.toString().string());
1231 return ret;
1232 }
1233 }
1234
1235 evictedClients.clear();
1236
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 // Once clients have been disconnected, relock
1238 mServiceLock.lock();
1239
1240 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1241 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1242 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001243 }
1244
Ruben Brunkcc776712015-02-17 20:18:47 -08001245 *partial = clientDescriptor;
1246 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001247}
1248
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001249Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001250 const sp<ICameraClient>& cameraClient,
1251 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001252 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001253 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001254 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001255 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001256 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001257
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001258 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001259 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001260 String8 id = String8::format("%d", cameraId);
1261 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001262 ret = connectHelper<ICameraClient,Client>(cameraClient, id,
1263 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1264 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1265 /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001266
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001267 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001268 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001269 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001270 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271 }
1272
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001273 *device = client;
1274 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275}
1276
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001277Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001278 const sp<ICameraClient>& cameraClient,
1279 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001280 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001281 int clientUid,
1282 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001283 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001284
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001285 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001286 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001287 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001288 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001289 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001290 /*
1291 * Either the HAL version is unspecified in which case this just creates
1292 * a camera client selected by the latest device version, or
1293 * it's a particular version in which case the HAL must supported
1294 * the open_legacy call
1295 */
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001296 String8 msg = String8::format("Camera HAL module version %x too old for connectLegacy!",
1297 apiVersion);
1298 ALOGE("%s: %s",
1299 __FUNCTION__, msg.string());
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001300 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001301 msg);
1302 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001303 }
1304
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001305 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001306 sp<Client> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001307 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion,
1308 clientPackageName, clientUid, USE_CALLING_PID, API_1,
1309 /*legacyMode*/ true, /*shimUpdateOnly*/ false,
1310 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001311
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001312 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001313 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001314 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001315 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001316 }
1317
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001318 *device = client;
1319 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001320}
1321
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001322Status CameraService::connectDevice(
1323 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Ruben Brunkcc776712015-02-17 20:18:47 -08001324 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001325 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001326 int clientUid,
1327 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001328 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001329
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001330 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001331 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001332 String8 id = String8::format("%d", cameraId);
1333 sp<CameraDeviceClient> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001334 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1335 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
1336 clientUid, USE_CALLING_PID, API_2,
1337 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1338 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001339
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001340 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001341 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001342 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001343 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001344 }
1345
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001346 *device = client;
1347 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001348}
1349
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001350Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001351 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001352
1353 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001354 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001355 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001356 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1357 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001358 }
1359
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001360 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001361 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001362
1363 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001364 auto state = getCameraState(id);
1365 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001366 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001367 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1368 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 }
1370
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001371 int32_t cameraStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1373 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001374 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001375 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1376 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001377 }
1378
1379 {
1380 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001381 int32_t status;
1382 status_t err = getTorchStatusLocked(id, &status);
1383 if (err != OK) {
1384 if (err == NAME_NOT_FOUND) {
1385 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1386 "Camera \"%s\" does not have a flash unit", id.string());
1387 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001388 ALOGE("%s: getting current torch status failed for camera %s",
1389 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001390 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1391 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1392 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001393 }
1394
1395 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001396 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001397 ALOGE("%s: torch mode of camera %s is not available because "
1398 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001399 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1400 "Torch for camera \"%s\" is not available due to an existing camera user",
1401 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001402 } else {
1403 ALOGE("%s: torch mode of camera %s is not available due to "
1404 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001405 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1406 "Torch for camera \"%s\" is not available due to insufficient resources",
1407 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001408 }
1409 }
1410 }
1411
Ruben Brunk99e69712015-05-26 17:25:07 -07001412 {
1413 // Update UID map - this is used in the torch status changed callbacks, so must be done
1414 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001415 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001416 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1417 mTorchUidMap[id].first = uid;
1418 mTorchUidMap[id].second = uid;
1419 } else {
1420 // Set the pending UID
1421 mTorchUidMap[id].first = uid;
1422 }
1423 }
1424
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001425 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001426
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001427 if (err != OK) {
1428 int32_t errorCode;
1429 String8 msg;
1430 switch (err) {
1431 case -ENOSYS:
1432 msg = String8::format("Camera \"%s\" has no flashlight",
1433 id.string());
1434 errorCode = ERROR_ILLEGAL_ARGUMENT;
1435 break;
1436 default:
1437 msg = String8::format(
1438 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1439 id.string(), enabled, strerror(-err), err);
1440 errorCode = ERROR_INVALID_OPERATION;
1441 }
1442 ALOGE("%s: %s", __FUNCTION__, msg.string());
1443 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001444 }
1445
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001446 {
1447 // update the link to client's death
1448 Mutex::Autolock al(mTorchClientMapMutex);
1449 ssize_t index = mTorchClientMap.indexOfKey(id);
1450 if (enabled) {
1451 if (index == NAME_NOT_FOUND) {
1452 mTorchClientMap.add(id, clientBinder);
1453 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001454 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001455 mTorchClientMap.replaceValueAt(index, clientBinder);
1456 }
1457 clientBinder->linkToDeath(this);
1458 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001459 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001460 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001461 }
1462
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001463 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001464}
1465
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001466Status CameraService::notifySystemEvent(int32_t eventId,
1467 const std::vector<int32_t>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001468 ATRACE_CALL();
1469
Ruben Brunk36597b22015-03-20 22:15:57 -07001470 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001471 case ICameraService::EVENT_USER_SWITCHED: {
1472 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001473 break;
1474 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001475 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001476 default: {
1477 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1478 eventId);
1479 break;
1480 }
1481 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001482 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001483}
1484
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001485Status CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001486 ATRACE_CALL();
1487
Igor Murashkinbfc99152013-02-27 12:55:20 -08001488 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001489
Ruben Brunk3450ba72015-06-16 11:00:37 -07001490 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001491 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001492 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001493 }
1494
Igor Murashkinbfc99152013-02-27 12:55:20 -08001495 Mutex::Autolock lock(mServiceLock);
1496
Ruben Brunkcc776712015-02-17 20:18:47 -08001497 {
1498 Mutex::Autolock lock(mStatusListenerLock);
1499 for (auto& it : mListenerList) {
1500 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1501 ALOGW("%s: Tried to add listener %p which was already subscribed",
1502 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001503 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001504 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001505 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001506
1507 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001508 }
1509
Igor Murashkinbfc99152013-02-27 12:55:20 -08001510
Igor Murashkincba2c162013-03-20 15:56:31 -07001511 /* Immediately signal current status to this listener only */
1512 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001513 Mutex::Autolock lock(mCameraStatesLock);
1514 for (auto& i : mCameraStates) {
1515 // TODO: Update binder to use String16 for camera IDs and remove;
1516 int id = cameraIdToInt(i.first);
1517 if (id == -1) continue;
1518
1519 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001520 }
1521 }
1522
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001523 /* Immediately signal current torch status to this listener only */
1524 {
1525 Mutex::Autolock al(mTorchStatusMutex);
1526 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001527 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1528 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001529 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001530 }
1531
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001532 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001533}
Ruben Brunkcc776712015-02-17 20:18:47 -08001534
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001535Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001536 ATRACE_CALL();
1537
Igor Murashkinbfc99152013-02-27 12:55:20 -08001538 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1539
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001540 if (listener == 0) {
1541 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001542 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001543 }
1544
Igor Murashkinbfc99152013-02-27 12:55:20 -08001545 Mutex::Autolock lock(mServiceLock);
1546
Ruben Brunkcc776712015-02-17 20:18:47 -08001547 {
1548 Mutex::Autolock lock(mStatusListenerLock);
1549 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1550 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1551 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001552 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001553 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001554 }
1555 }
1556
1557 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1558 __FUNCTION__, listener.get());
1559
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001560 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001561}
1562
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001563Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001564
1565 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001566 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1567
1568 if (parameters == NULL) {
1569 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001570 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001571 }
1572
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001573 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001574
1575 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001576 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001577 // Error logged by caller
1578 return ret;
1579 }
1580
1581 String8 shimParamsString8 = shimParams.flatten();
1582 String16 shimParamsString16 = String16(shimParamsString8);
1583
1584 *parameters = shimParamsString16;
1585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001586 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001587}
1588
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001589Status CameraService::supportsCameraApi(int cameraId, int apiVersion, bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001590 ATRACE_CALL();
1591
Igor Murashkin65d14b92014-06-17 12:03:20 -07001592 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1593
1594 switch (apiVersion) {
1595 case API_VERSION_1:
1596 case API_VERSION_2:
1597 break;
1598 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599 String8 msg = String8::format("Unknown API version %d", apiVersion);
1600 ALOGE("%s: %s", __FUNCTION__, msg.string());
1601 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001602 }
1603
1604 int facing = -1;
1605 int deviceVersion = getDeviceVersion(cameraId, &facing);
1606
1607 switch(deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 case CAMERA_DEVICE_API_VERSION_1_0:
1609 case CAMERA_DEVICE_API_VERSION_3_0:
1610 case CAMERA_DEVICE_API_VERSION_3_1:
1611 if (apiVersion == API_VERSION_2) {
1612 ALOGV("%s: Camera id %d uses HAL version %d <3.2, doesn't support api2 without shim",
1613 __FUNCTION__, cameraId, deviceVersion);
1614 *isSupported = false;
1615 } else { // if (apiVersion == API_VERSION_1) {
1616 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1617 __FUNCTION__, cameraId);
1618 *isSupported = true;
1619 }
1620 break;
1621 case CAMERA_DEVICE_API_VERSION_3_2:
1622 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001623 case CAMERA_DEVICE_API_VERSION_3_4:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001624 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
Igor Murashkin65d14b92014-06-17 12:03:20 -07001625 __FUNCTION__, cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626 *isSupported = true;
1627 break;
1628 case -1: {
1629 String8 msg = String8::format("Unknown camera ID %d", cameraId);
1630 ALOGE("%s: %s", __FUNCTION__, msg.string());
1631 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001632 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001633 default: {
1634 String8 msg = String8::format("Unknown device version %d for device %d",
1635 deviceVersion, cameraId);
1636 ALOGE("%s: %s", __FUNCTION__, msg.string());
1637 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1638 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07001639 }
1640
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001641 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001642}
1643
Ruben Brunkcc776712015-02-17 20:18:47 -08001644void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001645 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001646 for (auto& i : mActiveClientManager.getAll()) {
1647 auto clientSp = i->getValue();
1648 if (clientSp.get() == client) {
1649 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001650 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001651 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001652}
1653
Ruben Brunkcc776712015-02-17 20:18:47 -08001654bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1655 const int callingPid = getCallingPid();
1656 const int servicePid = getpid();
1657 bool ret = false;
1658 {
1659 // Acquire mServiceLock and prevent other clients from connecting
1660 std::unique_ptr<AutoConditionLock> lock =
1661 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001662
Igor Murashkin634a5152013-02-20 17:15:11 -08001663
Ruben Brunkcc776712015-02-17 20:18:47 -08001664 std::vector<sp<BasicClient>> evicted;
1665 for (auto& i : mActiveClientManager.getAll()) {
1666 auto clientSp = i->getValue();
1667 if (clientSp.get() == nullptr) {
1668 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1669 mActiveClientManager.remove(i);
1670 continue;
1671 }
1672 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1673 callingPid == clientSp->getClientPid())) {
1674 mActiveClientManager.remove(i);
1675 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001676
Ruben Brunkcc776712015-02-17 20:18:47 -08001677 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001678 clientSp->notifyError(
1679 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001680 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001681 }
1682 }
1683
Ruben Brunkcc776712015-02-17 20:18:47 -08001684 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1685 // other clients from connecting in mServiceLockWrapper if held
1686 mServiceLock.unlock();
1687
Ruben Brunk36597b22015-03-20 22:15:57 -07001688 // Do not clear caller identity, remote caller should be client proccess
1689
Ruben Brunkcc776712015-02-17 20:18:47 -08001690 for (auto& i : evicted) {
1691 if (i.get() != nullptr) {
1692 i->disconnect();
1693 ret = true;
1694 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001695 }
1696
Ruben Brunkcc776712015-02-17 20:18:47 -08001697 // Reacquire mServiceLock
1698 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001699
Ruben Brunkcc776712015-02-17 20:18:47 -08001700 } // lock is destroyed, allow further connect calls
1701
1702 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001703}
1704
Igor Murashkinecf17e82012-10-02 16:05:11 -07001705
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001706/**
1707 * Check camera capabilities, such as support for basic color operation
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001708 * Also check that the device HAL version is still in support
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001709 */
1710int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
Yin-Chia Yeh654b4bf2015-12-08 12:19:31 -08001711 // device_version undefined in CAMERA_MODULE_API_VERSION_1_0,
1712 // All CAMERA_MODULE_API_VERSION_1_0 devices are backward-compatible
1713 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
1714 // Verify the device version is in the supported range
1715 switch (info.device_version) {
1716 case CAMERA_DEVICE_API_VERSION_1_0:
1717 case CAMERA_DEVICE_API_VERSION_3_0:
1718 case CAMERA_DEVICE_API_VERSION_3_1:
1719 case CAMERA_DEVICE_API_VERSION_3_2:
1720 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001721 case CAMERA_DEVICE_API_VERSION_3_4:
Yin-Chia Yeh654b4bf2015-12-08 12:19:31 -08001722 // in support
1723 break;
1724 case CAMERA_DEVICE_API_VERSION_2_0:
1725 case CAMERA_DEVICE_API_VERSION_2_1:
1726 // no longer supported
1727 default:
1728 ALOGE("%s: Device %d has HAL version %x, which is not supported",
1729 __FUNCTION__, id, info.device_version);
1730 String8 msg = String8::format(
1731 "Unsupported device HAL version %x for device %d",
1732 info.device_version, id);
1733 logServiceError(msg.string(), NO_INIT);
1734 return NO_INIT;
1735 }
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001736 }
1737
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001738 // Assume all devices pre-v3.3 are backward-compatible
1739 bool isBackwardCompatible = true;
1740 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1741 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1742 isBackwardCompatible = false;
1743 status_t res;
1744 camera_metadata_ro_entry_t caps;
1745 res = find_camera_metadata_ro_entry(
1746 info.static_camera_characteristics,
1747 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1748 &caps);
1749 if (res != 0) {
1750 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1751 __FUNCTION__, id);
1752 caps.count = 0;
1753 }
1754 for (size_t i = 0; i < caps.count; i++) {
1755 if (caps.data.u8[i] ==
1756 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1757 isBackwardCompatible = true;
1758 break;
1759 }
1760 }
1761 }
1762
1763 if (!isBackwardCompatible) {
1764 mNumberOfNormalCameras--;
1765 *latestStrangeCameraId = id;
1766 } else {
1767 if (id > *latestStrangeCameraId) {
1768 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1769 "This is not allowed due backward-compatibility requirements",
1770 __FUNCTION__, id, *latestStrangeCameraId);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001771 logServiceError("Invalid order of camera devices", NO_INIT);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001772 mNumberOfCameras = 0;
1773 mNumberOfNormalCameras = 0;
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001774 return NO_INIT;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001775 }
1776 }
1777 return OK;
1778}
1779
Ruben Brunkcc776712015-02-17 20:18:47 -08001780std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1781 const String8& cameraId) const {
1782 std::shared_ptr<CameraState> state;
1783 {
1784 Mutex::Autolock lock(mCameraStatesLock);
1785 auto iter = mCameraStates.find(cameraId);
1786 if (iter != mCameraStates.end()) {
1787 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 }
1789 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001790 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791}
1792
Ruben Brunkcc776712015-02-17 20:18:47 -08001793sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1794 // Remove from active clients list
1795 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1796 if (clientDescriptorPtr == nullptr) {
1797 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1798 cameraId.string());
1799 return sp<BasicClient>{nullptr};
1800 }
1801
1802 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001803}
1804
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001805void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001806 // Acquire mServiceLock and prevent other clients from connecting
1807 std::unique_ptr<AutoConditionLock> lock =
1808 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1809
Ruben Brunk6267b532015-04-30 17:44:07 -07001810 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001811 for (size_t i = 0; i < newUserIds.size(); i++) {
1812 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001813 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001814 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07001815 return;
1816 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001817 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001818 }
1819
Ruben Brunka8ca9152015-04-07 14:23:40 -07001820
Ruben Brunk6267b532015-04-30 17:44:07 -07001821 if (newAllowedUsers == mAllowedUsers) {
1822 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1823 return;
1824 }
1825
1826 logUserSwitch(mAllowedUsers, newAllowedUsers);
1827
1828 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001829
1830 // Current user has switched, evict all current clients.
1831 std::vector<sp<BasicClient>> evicted;
1832 for (auto& i : mActiveClientManager.getAll()) {
1833 auto clientSp = i->getValue();
1834
1835 if (clientSp.get() == nullptr) {
1836 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1837 continue;
1838 }
1839
Ruben Brunk6267b532015-04-30 17:44:07 -07001840 // Don't evict clients that are still allowed.
1841 uid_t clientUid = clientSp->getClientUid();
1842 userid_t clientUserId = multiuser_get_user_id(clientUid);
1843 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1844 continue;
1845 }
1846
Ruben Brunk36597b22015-03-20 22:15:57 -07001847 evicted.push_back(clientSp);
1848
1849 String8 curTime = getFormattedCurrentTime();
1850
1851 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1852 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001853
Ruben Brunk36597b22015-03-20 22:15:57 -07001854 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001855 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001856 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001857 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1858 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001859
1860 }
1861
1862 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1863 // blocking other clients from connecting in mServiceLockWrapper if held.
1864 mServiceLock.unlock();
1865
1866 // Clear caller identity temporarily so client disconnect PID checks work correctly
1867 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1868
1869 for (auto& i : evicted) {
1870 i->disconnect();
1871 }
1872
1873 IPCThreadState::self()->restoreCallingIdentity(token);
1874
1875 // Reacquire mServiceLock
1876 mServiceLock.lock();
1877}
Ruben Brunkcc776712015-02-17 20:18:47 -08001878
Ruben Brunka8ca9152015-04-07 14:23:40 -07001879void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001880 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001881 Mutex::Autolock l(mLogLock);
1882 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883}
1884
Ruben Brunka8ca9152015-04-07 14:23:40 -07001885void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001886 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001887 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001888 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001889 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001890}
1891
1892void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001893 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001894 // Log the clients evicted
1895 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001896 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001897}
1898
1899void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001900 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001901 // Log the client rejected
1902 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001903 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001904}
1905
Ruben Brunk6267b532015-04-30 17:44:07 -07001906void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1907 const std::set<userid_t>& newUserIds) {
1908 String8 newUsers = toString(newUserIds);
1909 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001910 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001911 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1912 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001913}
1914
1915void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1916 // Log the device removal
1917 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1918}
1919
1920void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1921 // Log the device removal
1922 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1923}
1924
1925void CameraService::logClientDied(int clientPid, const char* reason) {
1926 // Log the device removal
1927 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001928}
1929
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001930void CameraService::logServiceError(const char* msg, int errorCode) {
1931 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001932 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001933}
1934
Ruben Brunk36597b22015-03-20 22:15:57 -07001935status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1936 uint32_t flags) {
1937
1938 const int pid = getCallingPid();
1939 const int selfPid = getpid();
1940
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 // Permission checks
1942 switch (code) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001943 case BnCameraService::NOTIFYSYSTEMEVENT: {
Ruben Brunk36597b22015-03-20 22:15:57 -07001944 if (pid != selfPid) {
1945 // Ensure we're being called by system_server, or similar process with
1946 // permissions to notify the camera service about system events
1947 if (!checkCallingPermission(
1948 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1949 const int uid = getCallingUid();
1950 ALOGE("Permission Denial: cannot send updates to camera service about system"
1951 " events from pid=%d, uid=%d", pid, uid);
1952 return PERMISSION_DENIED;
1953 }
1954 }
1955 break;
1956 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957 }
1958
1959 return BnCameraService::onTransact(code, data, reply, flags);
1960}
1961
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962// We share the media players for shutter and recording sound for all clients.
1963// A reference count is kept to determine when we will actually release the
1964// media players.
1965
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001966MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001968 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001969 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 mp->prepare();
1971 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001972 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 return NULL;
1974 }
1975 return mp;
1976}
1977
1978void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001979 ATRACE_CALL();
1980
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 Mutex::Autolock lock(mSoundLock);
1982 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1983 if (mSoundRef++) return;
1984
1985 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001986 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1987 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988}
1989
1990void CameraService::releaseSound() {
1991 Mutex::Autolock lock(mSoundLock);
1992 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1993 if (--mSoundRef) return;
1994
1995 for (int i = 0; i < NUM_SOUNDS; i++) {
1996 if (mSoundPlayer[i] != 0) {
1997 mSoundPlayer[i]->disconnect();
1998 mSoundPlayer[i].clear();
1999 }
2000 }
2001}
2002
2003void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002004 ATRACE_CALL();
2005
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 LOG1("playSound(%d)", kind);
2007 Mutex::Autolock lock(mSoundLock);
2008 sp<MediaPlayer> player = mSoundPlayer[kind];
2009 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002010 player->seekTo(0);
2011 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 }
2013}
2014
2015// ----------------------------------------------------------------------------
2016
2017CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002018 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002019 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002020 int cameraId, int cameraFacing,
2021 int clientPid, uid_t clientUid,
2022 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002023 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002024 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002025 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002026 cameraId, cameraFacing,
2027 clientPid, clientUid,
2028 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08002029{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002031 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002033 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002036
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002037 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038}
2039
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040// tear down the client
2041CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002042 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002043 mDestructionStarted = true;
2044
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07002045 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002046 // unconditionally disconnect. function is idempotent
2047 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048}
2049
Igor Murashkin634a5152013-02-20 17:15:11 -08002050CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002051 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002052 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002053 int cameraId, int cameraFacing,
2054 int clientPid, uid_t clientUid,
2055 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002056 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08002057{
2058 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002059 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08002060 mCameraId = cameraId;
2061 mCameraFacing = cameraFacing;
2062 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002063 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08002064 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002065 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002066 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002067
2068 // In some cases the calling code has no access to the package it runs under.
2069 // For example, NDK camera API.
2070 // In this case we will get the packages for the calling UID and pick the first one
2071 // for attributing the app op. This will work correctly for runtime permissions
2072 // as for legacy apps we will toggle the app op for all packages in the UID.
2073 // The caveat is that the operation may be attributed to the wrong package and
2074 // stats based on app ops may be slightly off.
2075 if (mClientPackageName.size() <= 0) {
2076 sp<IServiceManager> sm = defaultServiceManager();
2077 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2078 if (binder == 0) {
2079 ALOGE("Cannot get permission service");
2080 // Leave mClientPackageName unchanged (empty) and the further interaction
2081 // with camera will fail in BasicClient::startCameraOps
2082 return;
2083 }
2084
2085 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2086 Vector<String16> packages;
2087
2088 permCtrl->getPackagesForUid(mClientUid, packages);
2089
2090 if (packages.isEmpty()) {
2091 ALOGE("No packages for calling UID");
2092 // Leave mClientPackageName unchanged (empty) and the further interaction
2093 // with camera will fail in BasicClient::startCameraOps
2094 return;
2095 }
2096 mClientPackageName = packages[0];
2097 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002098}
2099
2100CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002101 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002102 mDestructionStarted = true;
2103}
2104
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002105binder::Status CameraService::BasicClient::disconnect() {
2106 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002107 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002108 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002109 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002110 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002111
2112 mCameraService->removeByClient(this);
2113 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002114 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08002115
2116 sp<IBinder> remote = getRemote();
2117 if (remote != nullptr) {
2118 remote->unlinkToDeath(mCameraService);
2119 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002120
2121 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002122 // Notify flashlight that a camera device is closed.
2123 mCameraService->mFlashlight->deviceClosed(String8::format("%d", mCameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08002124 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
2125
Igor Murashkincba2c162013-03-20 15:56:31 -07002126 // client shouldn't be able to call into us anymore
2127 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002128
2129 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002130}
2131
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002132status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2133 // No dumping of clients directly over Binder,
2134 // must go through CameraService::dump
2135 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2136 IPCThreadState::self()->getCallingUid(), NULL, 0);
2137 return OK;
2138}
2139
Ruben Brunkcc776712015-02-17 20:18:47 -08002140String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002141 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002142}
2143
2144
2145int CameraService::BasicClient::getClientPid() const {
2146 return mClientPid;
2147}
2148
Ruben Brunk6267b532015-04-30 17:44:07 -07002149uid_t CameraService::BasicClient::getClientUid() const {
2150 return mClientUid;
2151}
2152
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002153bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2154 // Defaults to API2.
2155 return level == API_2;
2156}
2157
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002158status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002159 ATRACE_CALL();
2160
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002161 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002162 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002163 mOpsCallback = new OpsCallback(this);
2164
Igor Murashkine6800ce2013-03-04 17:25:57 -08002165 {
2166 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002167 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002168 }
2169
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002170 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002171 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002172 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002173 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002174
Svetoslav28e8ef72015-05-11 19:21:31 -07002175 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002176 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002177 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002178 return PERMISSION_DENIED;
2179 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002180
Svetoslav28e8ef72015-05-11 19:21:31 -07002181 if (res == AppOpsManager::MODE_IGNORED) {
2182 ALOGI("Camera %d: Access for \"%s\" has been restricted",
2183 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002184 // Return the same error as for device policy manager rejection
2185 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002186 }
2187
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002188 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002189
2190 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2191 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002192 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002193
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002194 // Transition device state to OPEN
2195 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2196 String8::format("%d", mCameraId));
2197
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002198 return OK;
2199}
2200
2201status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002202 ATRACE_CALL();
2203
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002204 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002205 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002206 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002207 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002208 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002209 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002210
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002211 std::initializer_list<int32_t> rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002212 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002213
Ruben Brunkcc776712015-02-17 20:18:47 -08002214 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002215 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002216 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002217
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002218 // Transition device state to CLOSED
2219 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2220 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002221 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002222 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002223 if (mOpsCallback != NULL) {
2224 mAppOpsManager.stopWatchingMode(mOpsCallback);
2225 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002226 mOpsCallback.clear();
2227
2228 return OK;
2229}
2230
2231void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002232 ATRACE_CALL();
2233
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002234 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002235 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002236
2237 if (op != AppOpsManager::OP_CAMERA) {
2238 ALOGW("Unexpected app ops notification received: %d", op);
2239 return;
2240 }
2241
2242 int32_t res;
2243 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002244 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002245 ALOGV("checkOp returns: %d, %s ", res,
2246 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2247 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2248 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2249 "UNKNOWN");
2250
2251 if (res != AppOpsManager::MODE_ALLOWED) {
2252 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2253 myName.string());
2254 // Reset the client PID to allow server-initiated disconnect,
2255 // and to prevent further calls by client.
2256 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002257 CaptureResultExtras resultExtras; // a dummy result (invalid)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002258 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002259 disconnect();
2260 }
2261}
2262
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263// ----------------------------------------------------------------------------
2264
Ruben Brunkcc776712015-02-17 20:18:47 -08002265// Provide client strong pointer for callbacks.
2266sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2267 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2268 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2269 if (clientDescriptor != nullptr) {
2270 return sp<Client>{
2271 static_cast<Client*>(clientDescriptor->getValue().get())};
2272 }
2273 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274}
2275
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002276void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002277 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002278 (void) errorCode;
2279 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002280 if (mRemoteCallback != NULL) {
2281 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2282 } else {
2283 ALOGE("mRemoteCallback is NULL!!");
2284 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002285}
2286
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002287// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002288binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002289 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002290 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002291}
2292
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002293bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2294 return level == API_1;
2295}
2296
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002297CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2298 mClient(client) {
2299}
2300
2301void CameraService::Client::OpsCallback::opChanged(int32_t op,
2302 const String16& packageName) {
2303 sp<BasicClient> client = mClient.promote();
2304 if (client != NULL) {
2305 client->opChanged(op, packageName);
2306 }
2307}
2308
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002310// CameraState
2311// ----------------------------------------------------------------------------
2312
2313CameraService::CameraState::CameraState(const String8& id, int cost,
2314 const std::set<String8>& conflicting) : mId(id),
2315 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2316
2317CameraService::CameraState::~CameraState() {}
2318
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002319int32_t CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002320 Mutex::Autolock lock(mStatusLock);
2321 return mStatus;
2322}
2323
2324CameraParameters CameraService::CameraState::getShimParams() const {
2325 return mShimParams;
2326}
2327
2328void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2329 mShimParams = params;
2330}
2331
2332int CameraService::CameraState::getCost() const {
2333 return mCost;
2334}
2335
2336std::set<String8> CameraService::CameraState::getConflicting() const {
2337 return mConflicting;
2338}
2339
2340String8 CameraService::CameraState::getId() const {
2341 return mId;
2342}
2343
2344// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002345// ClientEventListener
2346// ----------------------------------------------------------------------------
2347
2348void CameraService::ClientEventListener::onClientAdded(
2349 const resource_policy::ClientDescriptor<String8,
2350 sp<CameraService::BasicClient>>& descriptor) {
2351 auto basicClient = descriptor.getValue();
2352 if (basicClient.get() != nullptr) {
2353 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2354 notifier.noteStartCamera(descriptor.getKey(),
2355 static_cast<int>(basicClient->getClientUid()));
2356 }
2357}
2358
2359void CameraService::ClientEventListener::onClientRemoved(
2360 const resource_policy::ClientDescriptor<String8,
2361 sp<CameraService::BasicClient>>& descriptor) {
2362 auto basicClient = descriptor.getValue();
2363 if (basicClient.get() != nullptr) {
2364 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2365 notifier.noteStopCamera(descriptor.getKey(),
2366 static_cast<int>(basicClient->getClientUid()));
2367 }
2368}
2369
2370
2371// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002372// CameraClientManager
2373// ----------------------------------------------------------------------------
2374
Ruben Brunk99e69712015-05-26 17:25:07 -07002375CameraService::CameraClientManager::CameraClientManager() {
2376 setListener(std::make_shared<ClientEventListener>());
2377}
2378
Ruben Brunkcc776712015-02-17 20:18:47 -08002379CameraService::CameraClientManager::~CameraClientManager() {}
2380
2381sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2382 const String8& id) const {
2383 auto descriptor = get(id);
2384 if (descriptor == nullptr) {
2385 return sp<BasicClient>{nullptr};
2386 }
2387 return descriptor->getValue();
2388}
2389
2390String8 CameraService::CameraClientManager::toString() const {
2391 auto all = getAll();
2392 String8 ret("[");
2393 bool hasAny = false;
2394 for (auto& i : all) {
2395 hasAny = true;
2396 String8 key = i->getKey();
2397 int32_t cost = i->getCost();
2398 int32_t pid = i->getOwnerId();
2399 int32_t priority = i->getPriority();
2400 auto conflicting = i->getConflicting();
2401 auto clientSp = i->getValue();
2402 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002403 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002404 if (clientSp.get() != nullptr) {
2405 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002406 uid_t clientUid = clientSp->getClientUid();
2407 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002408 }
2409 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2410 PRId32 ", ", key.string(), cost, pid, priority);
2411
Ruben Brunk6267b532015-04-30 17:44:07 -07002412 if (clientSp.get() != nullptr) {
2413 ret.appendFormat("User Id: %d, ", clientUserId);
2414 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002415 if (packageName.size() != 0) {
2416 ret.appendFormat("Client Package Name: %s", packageName.string());
2417 }
2418
2419 ret.append(", Conflicting Client Devices: {");
2420 for (auto& j : conflicting) {
2421 ret.appendFormat("%s, ", j.string());
2422 }
2423 ret.append("})");
2424 }
2425 if (hasAny) ret.append("\n");
2426 ret.append("]\n");
2427 return ret;
2428}
2429
2430CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2431 const String8& key, const sp<BasicClient>& value, int32_t cost,
2432 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2433
2434 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2435 key, value, cost, conflictingKeys, priority, ownerId);
2436}
2437
2438CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2439 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2440 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2441 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2442}
2443
2444// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445
2446static const int kDumpLockRetries = 50;
2447static const int kDumpLockSleep = 60000;
2448
2449static bool tryLock(Mutex& mutex)
2450{
2451 bool locked = false;
2452 for (int i = 0; i < kDumpLockRetries; ++i) {
2453 if (mutex.tryLock() == NO_ERROR) {
2454 locked = true;
2455 break;
2456 }
2457 usleep(kDumpLockSleep);
2458 }
2459 return locked;
2460}
2461
2462status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002463 ATRACE_CALL();
2464
Ruben Brunka8ca9152015-04-07 14:23:40 -07002465 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002467 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 "can't dump CameraService from pid=%d, uid=%d\n",
2469 getCallingPid(),
2470 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 write(fd, result.string(), result.size());
2472 } else {
2473 bool locked = tryLock(mServiceLock);
2474 // failed to lock - CameraService is probably deadlocked
2475 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002476 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002477 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 }
2479
2480 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002481 if (!mModule) {
2482 result = String8::format("No camera module available!\n");
2483 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002484
2485 // Dump event log for error information
2486 dumpEventLog(fd);
2487
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002488 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002489 return NO_ERROR;
2490 }
2491
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002492 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2493 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2494 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2495 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002496 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
Eino-Ville Talvala49c97052016-01-12 14:29:40 -08002497 result.appendFormat("Number of normal camera devices: %d\n", mNumberOfNormalCameras);
Ruben Brunkcc776712015-02-17 20:18:47 -08002498 String8 activeClientString = mActiveClientManager.toString();
2499 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002500 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002501
Ruben Brunkf81648e2014-04-17 16:14:57 -07002502 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2503 if (desc == NULL) {
2504 result.appendFormat("Vendor tags left unimplemented.\n");
2505 } else {
2506 result.appendFormat("Vendor tag definitions:\n");
2507 }
2508
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002509 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002510
2511 if (desc != NULL) {
2512 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2513 }
2514
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002515 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002516
2517 bool stateLocked = tryLock(mCameraStatesLock);
2518 if (!stateLocked) {
2519 result = String8::format("CameraStates in use, may be deadlocked\n");
2520 write(fd, result.string(), result.size());
2521 }
2522
2523 for (auto& state : mCameraStates) {
2524 String8 cameraId = state.first;
2525 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002526 camera_info info;
2527
Ruben Brunkcc776712015-02-17 20:18:47 -08002528 // TODO: Change getCameraInfo + HAL to use String cameraIds
2529 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002530 if (rc != OK) {
2531 result.appendFormat(" Error reading static information!\n");
2532 write(fd, result.string(), result.size());
2533 } else {
2534 result.appendFormat(" Facing: %s\n",
Yin-Chia Yeh13cd59a2016-11-29 12:13:15 -08002535 info.facing == CAMERA_FACING_BACK ? "BACK" :
2536 info.facing == CAMERA_FACING_FRONT ? "FRONT" : "EXTERNAL");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002537 result.appendFormat(" Orientation: %d\n", info.orientation);
2538 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002539 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002540 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2541 } else {
2542 deviceVersion = info.device_version;
2543 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002544
2545 auto conflicting = state.second->getConflicting();
2546 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2547 result.appendFormat(" Conflicting Devices:");
2548 for (auto& id : conflicting) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002549 result.appendFormat(" %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002550 }
2551 if (conflicting.size() == 0) {
2552 result.appendFormat(" NONE");
2553 }
2554 result.appendFormat("\n");
2555
2556 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002557 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002558 result.appendFormat(" Device static metadata:\n");
2559 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002560 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002561 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002562 } else {
2563 write(fd, result.string(), result.size());
2564 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002565
2566 CameraParameters p = state.second->getShimParams();
2567 if (!p.isEmpty()) {
2568 result = String8::format(" Camera1 API shim is using parameters:\n ");
2569 write(fd, result.string(), result.size());
2570 p.dump(fd, args);
2571 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002572 }
2573
Ruben Brunkcc776712015-02-17 20:18:47 -08002574 auto clientDescriptor = mActiveClientManager.get(cameraId);
2575 if (clientDescriptor == nullptr) {
2576 result = String8::format(" Device %s is closed, no client instance\n",
2577 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002578 write(fd, result.string(), result.size());
2579 continue;
2580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002582 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2583 cameraId.string());
2584 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2585 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2586
2587 auto client = clientDescriptor->getValue();
2588 result.appendFormat("Client package: %s\n",
2589 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002590 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002591
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002592 client->dumpClient(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002594
2595 if (stateLocked) mCameraStatesLock.unlock();
2596
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002598 result = String8::format("\nNo active camera clients yet.\n");
2599 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 }
2601
2602 if (locked) mServiceLock.unlock();
2603
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002604 // Dump camera traces if there were any
2605 write(fd, "\n", 1);
2606 camera3::CameraTraces::dump(fd, args);
2607
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -07002608 // Process dump arguments, if any
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609 int n = args.size();
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -07002610 String16 verboseOption("-v");
2611 String16 unreachableOption("--unreachable");
2612 for (int i = 0; i < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002613 if (args[i] == verboseOption) {
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -07002614 // change logging level
2615 if (i + 1 >= n) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 String8 levelStr(args[i+1]);
2617 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002618 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002620 write(fd, result.string(), result.size());
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -07002621 } else if (args[i] == unreachableOption) {
2622 // Dump memory analysis
2623 // TODO - should limit be an argument parameter?
2624 UnreachableMemoryInfo info;
2625 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
2626 if (!success) {
2627 dprintf(fd, "\nUnable to dump unreachable memory. "
2628 "Try disabling SELinux enforcement.\n");
2629 } else {
2630 dprintf(fd, "\nDumping unreachable memory:\n");
2631 std::string s = info.ToString(/*log_contents*/ true);
2632 write(fd, s.c_str(), s.size());
2633 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634 }
2635 }
2636 }
2637 return NO_ERROR;
2638}
2639
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002640void CameraService::dumpEventLog(int fd) {
2641 String8 result = String8("\nPrior client events (most recent at top):\n");
2642
2643 Mutex::Autolock l(mLogLock);
2644 for (const auto& msg : mEventLog) {
2645 result.appendFormat(" %s\n", msg.string());
2646 }
2647
2648 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2649 result.append(" ...\n");
2650 } else if (mEventLog.size() == 0) {
2651 result.append(" [no events yet]\n");
2652 }
2653 result.append("\n");
2654
2655 write(fd, result.string(), result.size());
2656}
2657
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002658void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002659 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002660 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2661 if (mTorchClientMap[i] == who) {
2662 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002663 String8 cameraId = mTorchClientMap.keyAt(i);
2664 status_t res = mFlashlight->setTorchMode(cameraId, false);
2665 if (res) {
2666 ALOGE("%s: torch client died but couldn't turn off torch: "
2667 "%s (%d)", __FUNCTION__, strerror(-res), res);
2668 return;
2669 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002670 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002671 break;
2672 }
2673 }
2674}
2675
Ruben Brunkcc776712015-02-17 20:18:47 -08002676/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002677
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002678 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002679 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2680 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002681 */
2682
Ruben Brunka8ca9152015-04-07 14:23:40 -07002683 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2684
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002685 // check torch client
2686 handleTorchClientBinderDied(who);
2687
2688 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002689 if(!evictClientIdByRemote(who)) {
2690 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002691 return;
2692 }
2693
Ruben Brunkcc776712015-02-17 20:18:47 -08002694 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2695 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002696}
2697
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002698void CameraService::updateStatus(int32_t status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002699 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002700}
2701
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002702void CameraService::updateStatus(int32_t status, const String8& cameraId,
2703 std::initializer_list<int32_t> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002704 // Do not lock mServiceLock here or can get into a deadlock from
2705 // connect() -> disconnect -> updateStatus
2706
2707 auto state = getCameraState(cameraId);
2708
2709 if (state == nullptr) {
2710 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2711 cameraId.string());
2712 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002713 }
2714
Ruben Brunkcc776712015-02-17 20:18:47 -08002715 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2716 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2717 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002718 (const String8& cameraId, int32_t status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002719
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002720 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2721 // Update torch status if it has a flash unit.
2722 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002723 int32_t torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002724 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2725 NAME_NOT_FOUND) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002726 int32_t newTorchStatus =
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002727 status == ICameraServiceListener::STATUS_PRESENT ?
2728 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2729 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2730 if (torchStatus != newTorchStatus) {
2731 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2732 }
2733 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002734 }
2735
2736 Mutex::Autolock lock(mStatusListenerLock);
2737
2738 for (auto& listener : mListenerList) {
2739 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2740 int id = cameraIdToInt(cameraId);
2741 if (id != -1) listener->onStatusChanged(status, id);
2742 }
2743 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002744}
2745
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002746void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2747 const String8& cameraId) {
2748 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2749 if (proxyBinder == nullptr) return;
2750 String16 id(cameraId);
2751 proxyBinder->notifyCameraState(id, newState);
2752}
2753
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002754status_t CameraService::getTorchStatusLocked(
2755 const String8& cameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002756 int32_t *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002757 if (!status) {
2758 return BAD_VALUE;
2759 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002760 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2761 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002762 // invalid camera ID or the camera doesn't have a flash unit
2763 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002764 }
2765
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002766 *status = mTorchStatusMap.valueAt(index);
2767 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002768}
2769
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002770status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002771 int32_t status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002772 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2773 if (index == NAME_NOT_FOUND) {
2774 return BAD_VALUE;
2775 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002776 int32_t& item =
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002777 mTorchStatusMap.editValueAt(index);
2778 item = status;
2779
2780 return OK;
2781}
2782
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783}; // namespace android