blob: 5c490b2ddb75fbaf6bb3e6be552328534a35c32b [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080031#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryBase.h>
35#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080036#include <binder/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070038#include <cutils/properties.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080039#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <hardware/hardware.h>
41#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080042#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070044#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/Errors.h>
46#include <utils/Log.h>
47#include <utils/String16.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080048#include <utils/Trace.h>
49#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070050#include <system/camera_metadata.h>
51#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070054#include "api1/CameraClient.h"
55#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070057#include "utils/CameraTraces.h"
Igor Murashkin98e24722013-06-19 19:51:04 -070058#include "CameraDeviceFactory.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
60namespace android {
61
62// ----------------------------------------------------------------------------
63// Logging support -- this is for debugging only
64// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070065volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Steve Blockb8a80522011-12-20 16:23:08 +000067#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
70static void setLogLevel(int level) {
71 android_atomic_write(level, &gLogLevel);
72}
73
74// ----------------------------------------------------------------------------
75
Igor Murashkincba2c162013-03-20 15:56:31 -070076extern "C" {
77static void camera_device_status_change(
78 const struct camera_module_callbacks* callbacks,
79 int camera_id,
80 int new_status) {
81 sp<CameraService> cs = const_cast<CameraService*>(
Ruben Brunkcc776712015-02-17 20:18:47 -080082 static_cast<const CameraService*>(callbacks));
Igor Murashkincba2c162013-03-20 15:56:31 -070083
Ruben Brunkcc776712015-02-17 20:18:47 -080084 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
85 static_cast<camera_device_status_t>(new_status));
Igor Murashkincba2c162013-03-20 15:56:31 -070086}
Chien-Yu Chen3068d732015-02-09 13:29:57 -080087
88static void torch_mode_status_change(
89 const struct camera_module_callbacks* callbacks,
90 const char* camera_id,
91 int new_status) {
92 if (!callbacks || !camera_id) {
93 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
94 callbacks, camera_id);
95 }
96 sp<CameraService> cs = const_cast<CameraService*>(
97 static_cast<const CameraService*>(callbacks));
98
99 ICameraServiceListener::TorchStatus status;
100 switch (new_status) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800101 case TORCH_MODE_STATUS_NOT_AVAILABLE:
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800102 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
103 break;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800104 case TORCH_MODE_STATUS_AVAILABLE_OFF:
105 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
106 break;
107 case TORCH_MODE_STATUS_AVAILABLE_ON:
108 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800109 break;
110 default:
111 ALOGE("Unknown torch status %d", new_status);
112 return;
113 }
114
115 cs->onTorchStatusChanged(
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800116 String8(camera_id),
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800117 status);
118}
Igor Murashkincba2c162013-03-20 15:56:31 -0700119} // extern "C"
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
123// This is ugly and only safe if we never re-create the CameraService, but
124// should be ok for now.
125static CameraService *gCameraService;
126
Ruben Brunk6267b532015-04-30 17:44:07 -0700127CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH), mAllowedUsers(),
128 mSoundRef(0), mModule(0), mFlashlight(0) {
Steve Blockdf64d152012-01-04 20:05:49 +0000129 ALOGI("CameraService started (pid=%d)", getpid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130 gCameraService = this;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800131
Igor Murashkincba2c162013-03-20 15:56:31 -0700132 this->camera_device_status_change = android::camera_device_status_change;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800133 this->torch_mode_status_change = android::torch_mode_status_change;
134
Ruben Brunkcc776712015-02-17 20:18:47 -0800135 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136}
137
Iliyan Malchev8951a972011-04-14 16:55:59 -0700138void CameraService::onFirstRef()
139{
Ruben Brunkcc776712015-02-17 20:18:47 -0800140 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800141
Iliyan Malchev8951a972011-04-14 16:55:59 -0700142 BnCameraService::onFirstRef();
143
Ruben Brunk99e69712015-05-26 17:25:07 -0700144 // Update battery life tracking if service is restarting
145 BatteryNotifier& notifier(BatteryNotifier::getInstance());
146 notifier.noteResetCamera();
147 notifier.noteResetFlashlight();
148
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800149 camera_module_t *rawModule;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700150 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
151 (const hw_module_t **)&rawModule);
152 if (err < 0) {
153 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
154 logServiceError("Could not load camera HAL module", err);
Iliyan Malchev8951a972011-04-14 16:55:59 -0700155 mNumberOfCameras = 0;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700156 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700157 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800158
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700159 mModule = new CameraModule(rawModule);
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700160 err = mModule->init();
161 if (err != OK) {
162 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
163 strerror(-err));
164 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800165
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700166 mNumberOfCameras = 0;
167 delete mModule;
168 mModule = nullptr;
169 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700170 }
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700171 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700172
173 mNumberOfCameras = mModule->getNumberOfCameras();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700174 mNumberOfNormalCameras = mNumberOfCameras;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700175
Yin-Chia Yehd4a653a2015-10-14 11:05:44 -0700176 // Setup vendor tags before we call get_camera_info the first time
177 // because HAL might need to setup static vendor keys in get_camera_info
178 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
179 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
180 setUpVendorTags();
181 }
182
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700183 mFlashlight = new CameraFlashlight(*mModule, *this);
184 status_t res = mFlashlight->findFlashUnits();
185 if (res) {
186 // impossible because we haven't open any camera devices.
187 ALOGE("Failed to find flash units.");
188 }
189
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700190 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700191 for (int i = 0; i < mNumberOfCameras; i++) {
192 String8 cameraId = String8::format("%d", i);
193
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700194 // Get camera info
195
196 struct camera_info info;
197 bool haveInfo = true;
198 status_t rc = mModule->getCameraInfo(i, &info);
199 if (rc != NO_ERROR) {
200 ALOGE("%s: Received error loading camera info for device %d, cost and"
201 " conflicting devices fields set to defaults for this device.",
202 __FUNCTION__, i);
203 haveInfo = false;
204 }
205
206 // Check for backwards-compatibility support
207 if (haveInfo) {
208 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
209 delete mModule;
210 mModule = nullptr;
211 return;
212 }
213 }
214
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700215 // Defaults to use for cost and conflicting devices
216 int cost = 100;
217 char** conflicting_devices = nullptr;
218 size_t conflicting_devices_length = 0;
219
220 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700221 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
222 cost = info.resource_cost;
223 conflicting_devices = info.conflicting_devices;
224 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700225 }
226
227 std::set<String8> conflicting;
228 for (size_t i = 0; i < conflicting_devices_length; i++) {
229 conflicting.emplace(String8(conflicting_devices[i]));
230 }
231
232 // Initialize state for each camera device
233 {
234 Mutex::Autolock lock(mCameraStatesLock);
235 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
236 conflicting));
237 }
238
239 if (mFlashlight->hasFlashUnit(cameraId)) {
240 mTorchStatusMap.add(cameraId,
241 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
242 }
243 }
244
245 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
246 mModule->setCallbacks(this);
247 }
248
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700249 CameraDeviceFactory::registerService(this);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700250
251 CameraService::pingCameraServiceProxy();
252}
253
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700254sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Ruben Brunk2823ce02015-05-19 17:25:13 -0700255 sp<IServiceManager> sm = defaultServiceManager();
256 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
257 if (binder == nullptr) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700258 return nullptr;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700259 }
260 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700261 return proxyBinder;
262}
263
264void CameraService::pingCameraServiceProxy() {
265 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
266 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700267 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700268}
269
Mathias Agopian65ab4712010-07-14 17:59:35 -0700270CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800271 if (mModule) {
272 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800273 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800274 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800275 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800276 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277}
278
Ruben Brunkcc776712015-02-17 20:18:47 -0800279void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
280 camera_device_status_t newStatus) {
281 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700282 cameraId, newStatus);
283
Ruben Brunkcc776712015-02-17 20:18:47 -0800284 String8 id = String8::format("%d", cameraId);
285 std::shared_ptr<CameraState> state = getCameraState(id);
286
287 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700288 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
289 return;
290 }
291
Ruben Brunkcc776712015-02-17 20:18:47 -0800292 ICameraServiceListener::Status oldStatus = state->getStatus();
293
294 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
295 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700296 return;
297 }
298
Igor Murashkincba2c162013-03-20 15:56:31 -0700299 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700300 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
301 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800302 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700303 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800304 // Don't do this in updateStatus to avoid deadlock over mServiceLock
305 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700306
Ruben Brunkcc776712015-02-17 20:18:47 -0800307 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
308 // to this device until the status changes
309 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700310
Ruben Brunkcc776712015-02-17 20:18:47 -0800311 // Remove cached shim parameters
312 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700313
Ruben Brunkcc776712015-02-17 20:18:47 -0800314 // Remove the client from the list of active clients
315 clientToDisconnect = removeClientLocked(id);
316
317 // Notify the client of disconnection
Tom Keel5adc76c2015-10-08 16:42:56 +0200318 if (clientToDisconnect != nullptr) {
319 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
320 CaptureResultExtras{});
321 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700322 }
323
Ruben Brunkcc776712015-02-17 20:18:47 -0800324 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
325 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700326
Ruben Brunkcc776712015-02-17 20:18:47 -0800327 // Disconnect client
328 if (clientToDisconnect.get() != nullptr) {
329 // Ensure not in binder RPC so client disconnect PID checks work correctly
330 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
331 "onDeviceStatusChanged must be called from the camera service process!");
332 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700333 }
334
Ruben Brunkcc776712015-02-17 20:18:47 -0800335 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700336 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
337 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
338 newStatus));
339 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800340 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700341 }
342
Igor Murashkincba2c162013-03-20 15:56:31 -0700343}
344
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800345void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800346 ICameraServiceListener::TorchStatus newStatus) {
347 Mutex::Autolock al(mTorchStatusMutex);
348 onTorchStatusChangedLocked(cameraId, newStatus);
349}
350
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800351void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800352 ICameraServiceListener::TorchStatus newStatus) {
353 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
354 __FUNCTION__, cameraId.string(), newStatus);
355
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800356 ICameraServiceListener::TorchStatus status;
357 status_t res = getTorchStatusLocked(cameraId, &status);
358 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700359 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
360 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800361 return;
362 }
363 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800364 return;
365 }
366
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800367 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800368 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700369 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800370 return;
371 }
372
Ruben Brunkcc776712015-02-17 20:18:47 -0800373 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700374 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700375 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700376 auto iter = mTorchUidMap.find(cameraId);
377 if (iter != mTorchUidMap.end()) {
378 int oldUid = iter->second.second;
379 int newUid = iter->second.first;
380 BatteryNotifier& notifier(BatteryNotifier::getInstance());
381 if (oldUid != newUid) {
382 // If the UID has changed, log the status and update current UID in mTorchUidMap
383 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
384 notifier.noteFlashlightOff(cameraId, oldUid);
385 }
386 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
387 notifier.noteFlashlightOn(cameraId, newUid);
388 }
389 iter->second.second = newUid;
390 } else {
391 // If the UID has not changed, log the status
392 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
393 notifier.noteFlashlightOn(cameraId, oldUid);
394 } else {
395 notifier.noteFlashlightOff(cameraId, oldUid);
396 }
397 }
398 }
399 }
400
401 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800402 Mutex::Autolock lock(mStatusListenerLock);
403 for (auto& i : mListenerList) {
404 i->onTorchStatusChanged(newStatus, String16{cameraId});
405 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800406 }
407}
408
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700410 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700411 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
412}
413
414int32_t CameraService::getNumberOfCameras(int type) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700415 ATRACE_CALL();
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700416 switch (type) {
417 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
418 return mNumberOfNormalCameras;
419 case CAMERA_TYPE_ALL:
420 return mNumberOfCameras;
421 default:
422 ALOGW("%s: Unknown camera type %d, returning 0",
423 __FUNCTION__, type);
424 return 0;
425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426}
427
428status_t CameraService::getCameraInfo(int cameraId,
429 struct CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700430 ATRACE_CALL();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700431 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700432 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700433 }
434
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
436 return BAD_VALUE;
437 }
438
Iliyan Malchev8951a972011-04-14 16:55:59 -0700439 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700440 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800441 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700442 cameraInfo->facing = info.facing;
443 cameraInfo->orientation = info.orientation;
444 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445}
446
Ruben Brunkcc776712015-02-17 20:18:47 -0800447int CameraService::cameraIdToInt(const String8& cameraId) {
448 errno = 0;
449 size_t pos = 0;
450 int ret = stoi(std::string{cameraId.string()}, &pos);
451 if (errno != 0 || pos != cameraId.size()) {
452 return -1;
453 }
454 return ret;
455}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700456
457status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700458 ATRACE_CALL();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700459 status_t ret = OK;
460 struct CameraInfo info;
461 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
462 return ret;
463 }
464
465 CameraMetadata shimInfo;
466 int32_t orientation = static_cast<int32_t>(info.orientation);
467 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
468 return ret;
469 }
470
471 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
472 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
473 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
474 return ret;
475 }
476
Igor Murashkin65d14b92014-06-17 12:03:20 -0700477 CameraParameters shimParams;
478 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
479 // Error logged by callee
480 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700481 }
482
483 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700484 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700485 Vector<int32_t> formats;
486 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700487 {
488 shimParams.getSupportedPreviewSizes(/*out*/sizes);
489 shimParams.getSupportedPreviewFormats(/*out*/formats);
490 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700491 }
492
493 // Always include IMPLEMENTATION_DEFINED
494 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
495
496 const size_t INTS_PER_CONFIG = 4;
497
498 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700499 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
500
501 Vector<int32_t> streamConfigs;
502 streamConfigs.setCapacity(streamConfigSize);
503
Ruben Brunkb2119af2014-05-09 19:57:56 -0700504 for (size_t i = 0; i < formats.size(); ++i) {
505 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700506 streamConfigs.add(formats[i]);
507 streamConfigs.add(sizes[j].width);
508 streamConfigs.add(sizes[j].height);
509 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700510 }
511 }
512
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700513 for (size_t i = 0; i < jpegSizes.size(); ++i) {
514 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
515 streamConfigs.add(jpegSizes[i].width);
516 streamConfigs.add(jpegSizes[i].height);
517 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
518 }
519
Ruben Brunkb2119af2014-05-09 19:57:56 -0700520 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700521 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700522 return ret;
523 }
524
525 int64_t fakeMinFrames[0];
526 // TODO: Fixme, don't fake min frame durations.
527 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
528 fakeMinFrames, 0)) != OK) {
529 return ret;
530 }
531
532 int64_t fakeStalls[0];
533 // TODO: Fixme, don't fake stall durations.
534 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
535 fakeStalls, 0)) != OK) {
536 return ret;
537 }
538
539 *cameraInfo = shimInfo;
540 return OK;
541}
542
Zhijun He2b59be82013-09-25 10:14:30 -0700543status_t CameraService::getCameraCharacteristics(int cameraId,
544 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700545 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700546 if (!cameraInfo) {
547 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
548 return BAD_VALUE;
549 }
550
551 if (!mModule) {
552 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
553 return -ENODEV;
554 }
555
Zhijun He2b59be82013-09-25 10:14:30 -0700556 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
557 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
558 return BAD_VALUE;
559 }
560
561 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700562 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800563 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700564 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
565 /**
566 * Backwards compatibility mode for old HALs:
567 * - Convert CameraInfo into static CameraMetadata properties.
568 * - Retrieve cached CameraParameters for this camera. If none exist,
569 * attempt to open CameraClient and retrieve the CameraParameters.
570 * - Convert cached CameraParameters into static CameraMetadata
571 * properties.
572 */
573 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700574
Ruben Brunkb2119af2014-05-09 19:57:56 -0700575 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
576 return ret;
577 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700578
Ruben Brunkb2119af2014-05-09 19:57:56 -0700579 } else {
580 /**
581 * Normal HAL 2.1+ codepath.
582 */
583 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800584 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700585 *cameraInfo = info.static_camera_characteristics;
586 }
Zhijun He2b59be82013-09-25 10:14:30 -0700587
588 return ret;
589}
590
Ruben Brunkcc776712015-02-17 20:18:47 -0800591int CameraService::getCallingPid() {
592 return IPCThreadState::self()->getCallingPid();
593}
594
595int CameraService::getCallingUid() {
596 return IPCThreadState::self()->getCallingUid();
597}
598
599String8 CameraService::getFormattedCurrentTime() {
600 time_t now = time(nullptr);
601 char formattedTime[64];
602 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
603 return String8(formattedTime);
604}
605
606int CameraService::getCameraPriorityFromProcState(int procState) {
607 // Find the priority for the camera usage based on the process state. Higher priority clients
608 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700609 if (procState < 0) {
610 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
611 procState);
612 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800613 }
Eino-Ville Talvala52aad852015-09-03 12:24:24 -0700614 // Treat sleeping TOP processes the same as regular TOP processes, for
615 // access priority. This is important for lock-screen camera launch scenarios
616 if (procState == PROCESS_STATE_TOP_SLEEPING) {
617 procState = PROCESS_STATE_TOP;
618 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700619 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800620}
621
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800622status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700623 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800624 if (!mModule) {
625 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
626 return -ENODEV;
627 }
628
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800629 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
630 return OK;
631}
632
Igor Murashkin634a5152013-02-20 17:15:11 -0800633int CameraService::getDeviceVersion(int cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700634 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800635 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800636 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800637 return -1;
638 }
639
640 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800641 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800642 deviceVersion = info.device_version;
643 } else {
644 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
645 }
646
647 if (facing) {
648 *facing = info.facing;
649 }
650
651 return deviceVersion;
652}
653
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700654status_t CameraService::filterGetInfoErrorCode(status_t err) {
655 switch(err) {
656 case NO_ERROR:
657 case -EINVAL:
658 return err;
659 default:
660 break;
661 }
662 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800663}
664
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800665bool CameraService::setUpVendorTags() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700666 ATRACE_CALL();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800667 vendor_tag_ops_t vOps = vendor_tag_ops_t();
668
669 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800670 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800671 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
672 return false;
673 }
674
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800675 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800676
677 // Ensure all vendor operations are present
678 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
679 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
680 vOps.get_tag_type == NULL) {
681 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
682 , __FUNCTION__);
683 return false;
684 }
685
686 // Read all vendor tag definitions into a descriptor
687 sp<VendorTagDescriptor> desc;
688 status_t res;
689 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
690 != OK) {
691 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
692 "received error %s (%d). Camera clients will not be able to use"
693 "vendor tags", __FUNCTION__, strerror(res), res);
694 return false;
695 }
696
697 // Set the global descriptor to use with camera metadata
698 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
699 return true;
700}
701
Ruben Brunkcc776712015-02-17 20:18:47 -0800702status_t CameraService::makeClient(const sp<CameraService>& cameraService,
703 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
704 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
705 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
706 /*out*/sp<BasicClient>* client) {
707
708 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
709 int id = cameraIdToInt(cameraId);
710 if (id == -1) {
711 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
712 cameraId.string());
713 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700714 }
715
Ruben Brunkcc776712015-02-17 20:18:47 -0800716 if (halVersion < 0 || halVersion == deviceVersion) {
717 // Default path: HAL version is unspecified by caller, create CameraClient
718 // based on device version reported by the HAL.
719 switch(deviceVersion) {
720 case CAMERA_DEVICE_API_VERSION_1_0:
721 if (effectiveApiLevel == API_1) { // Camera1 API route
722 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
723 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
724 clientPid, clientUid, getpid(), legacyMode);
725 } else { // Camera2 API route
726 ALOGW("Camera using old HAL version: %d", deviceVersion);
727 return -EOPNOTSUPP;
728 }
729 break;
730 case CAMERA_DEVICE_API_VERSION_2_0:
731 case CAMERA_DEVICE_API_VERSION_2_1:
732 case CAMERA_DEVICE_API_VERSION_3_0:
733 case CAMERA_DEVICE_API_VERSION_3_1:
734 case CAMERA_DEVICE_API_VERSION_3_2:
735 case CAMERA_DEVICE_API_VERSION_3_3:
736 if (effectiveApiLevel == API_1) { // Camera1 API route
737 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
738 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
739 clientPid, clientUid, servicePid, legacyMode);
740 } else { // Camera2 API route
741 sp<ICameraDeviceCallbacks> tmp =
742 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
743 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
744 facing, clientPid, clientUid, servicePid);
745 }
746 break;
747 default:
748 // Should not be reachable
749 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
750 return INVALID_OPERATION;
751 }
752 } else {
753 // A particular HAL version is requested by caller. Create CameraClient
754 // based on the requested HAL version.
755 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
756 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
757 // Only support higher HAL version device opened as HAL1.0 device.
758 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
759 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
760 clientPid, clientUid, servicePid, legacyMode);
761 } else {
762 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
763 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
764 " opened as HAL %x device", halVersion, deviceVersion,
765 CAMERA_DEVICE_API_VERSION_1_0);
766 return INVALID_OPERATION;
767 }
768 }
769 return NO_ERROR;
770}
771
Ruben Brunk6267b532015-04-30 17:44:07 -0700772String8 CameraService::toString(std::set<userid_t> intSet) {
773 String8 s("");
774 bool first = true;
775 for (userid_t i : intSet) {
776 if (first) {
777 s.appendFormat("%d", i);
778 first = false;
779 } else {
780 s.appendFormat(", %d", i);
781 }
782 }
783 return s;
784}
785
Ruben Brunkcc776712015-02-17 20:18:47 -0800786status_t CameraService::initializeShimMetadata(int cameraId) {
787 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700788
789 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800790 String8 id = String8::format("%d", cameraId);
791 status_t ret = NO_ERROR;
792 sp<Client> tmp = nullptr;
793 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
794 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
795 false, true, tmp)) != NO_ERROR) {
796 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
797 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700798 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800799 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700800}
801
Igor Murashkin65d14b92014-06-17 12:03:20 -0700802status_t CameraService::getLegacyParametersLazy(int cameraId,
803 /*out*/
804 CameraParameters* parameters) {
805
806 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
807
808 status_t ret = 0;
809
810 if (parameters == NULL) {
811 ALOGE("%s: parameters must not be null", __FUNCTION__);
812 return BAD_VALUE;
813 }
814
Ruben Brunkcc776712015-02-17 20:18:47 -0800815 String8 id = String8::format("%d", cameraId);
816
817 // Check if we already have parameters
818 {
819 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700820 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800821 auto cameraState = getCameraState(id);
822 if (cameraState == nullptr) {
823 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
824 return BAD_VALUE;
825 }
826 CameraParameters p = cameraState->getShimParams();
827 if (!p.isEmpty()) {
828 *parameters = p;
829 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700830 }
831 }
832
Ruben Brunkcc776712015-02-17 20:18:47 -0800833 int64_t token = IPCThreadState::self()->clearCallingIdentity();
834 ret = initializeShimMetadata(cameraId);
835 IPCThreadState::self()->restoreCallingIdentity(token);
836 if (ret != NO_ERROR) {
837 // Error already logged by callee
838 return ret;
839 }
840
841 // Check for parameters again
842 {
843 // Scope for service lock
844 Mutex::Autolock lock(mServiceLock);
845 auto cameraState = getCameraState(id);
846 if (cameraState == nullptr) {
847 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
848 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700849 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800850 CameraParameters p = cameraState->getShimParams();
851 if (!p.isEmpty()) {
852 *parameters = p;
853 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700854 }
855 }
856
Ruben Brunkcc776712015-02-17 20:18:47 -0800857 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
858 __FUNCTION__);
859 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700860}
861
Ruben Brunk36597b22015-03-20 22:15:57 -0700862status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
863 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800864
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500866
Iliyan Malchev8951a972011-04-14 16:55:59 -0700867 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800868 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
869 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700870 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700871 }
872
Ruben Brunkcc776712015-02-17 20:18:47 -0800873 if (getCameraState(cameraId) == nullptr) {
874 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
875 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700876 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700877 }
878
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800879#if !defined(__BRILLO__)
880 status_t allowed = validateClientPermissionsLocked(cameraId, clientUid);
881 if (allowed != OK) {
882 return allowed;
883 }
884#endif // defined(__BRILLO__)
885
886 return checkIfDeviceIsUsable(cameraId);
887}
888
889status_t CameraService::validateClientPermissionsLocked(const String8& cameraId, int& clientUid)
890 const {
891 int callingPid = getCallingPid();
892
893 if (clientUid == USE_CALLING_UID) {
894 clientUid = getCallingUid();
895 } else {
896 // We only trust our own process to forward client UIDs
897 if (callingPid != getpid()) {
898 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
899 callingPid, clientUid);
900 return PERMISSION_DENIED;
901 }
902 }
903
Ruben Brunkcc776712015-02-17 20:18:47 -0800904 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800905 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800906 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700907 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800908 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
909 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800910 if (strcmp(value, "1") == 0) {
911 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800912 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
913 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700914 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800915 }
916
Ruben Brunka8ca9152015-04-07 14:23:40 -0700917 // Only allow clients who are being used by the current foreground device user, unless calling
918 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700919 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
920 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
921 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
922 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700923 return PERMISSION_DENIED;
924 }
925
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800926 return OK;
Ruben Brunkcc776712015-02-17 20:18:47 -0800927}
928
929status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
930 auto cameraState = getCameraState(cameraId);
931 int callingPid = getCallingPid();
932 if (cameraState == nullptr) {
933 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
934 cameraId.string());
935 return -ENODEV;
936 }
937
938 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700939 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800940 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
941 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700942 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700943 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800944 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
945 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700946 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700947 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700948
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800950}
951
Ruben Brunkcc776712015-02-17 20:18:47 -0800952void CameraService::finishConnectLocked(const sp<BasicClient>& client,
953 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800954
Ruben Brunkcc776712015-02-17 20:18:47 -0800955 // Make a descriptor for the incoming client
956 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
957 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
958
959 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
960 String8(client->getPackageName()));
961
962 if (evicted.size() > 0) {
963 // This should never happen - clients should already have been removed in disconnect
964 for (auto& i : evicted) {
965 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
966 __FUNCTION__, i->getKey().string());
967 }
968
969 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
970 __FUNCTION__);
971 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700972
973 // And register a death notification for the client callback. Do
974 // this last to avoid Binder policy where a nested Binder
975 // transaction might be pre-empted to service the client death
976 // notification if the client process dies before linkToDeath is
977 // invoked.
978 sp<IBinder> remoteCallback = client->getRemote();
979 if (remoteCallback != nullptr) {
980 remoteCallback->linkToDeath(this);
981 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800982}
983
984status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
985 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
986 /*out*/
987 sp<BasicClient>* client,
988 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700989 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -0800990 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700991 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800992 DescriptorPtr clientDescriptor;
993 {
994 if (effectiveApiLevel == API_1) {
995 // If we are using API1, any existing client for this camera ID with the same remote
996 // should be returned rather than evicted to allow MediaRecorder to work properly.
997
998 auto current = mActiveClientManager.get(cameraId);
999 if (current != nullptr) {
1000 auto clientSp = current->getValue();
1001 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001002 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1003 ALOGW("CameraService connect called from same client, but with a different"
1004 " API level, evicting prior client...");
1005 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001006 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001007 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001008 *client = clientSp;
1009 return NO_ERROR;
1010 }
1011 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001012 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001013 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001014
Ruben Brunkcc776712015-02-17 20:18:47 -08001015 // Return error if the device was unplugged or removed by the HAL for some reason
1016 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1017 return ret;
1018 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001019
Ruben Brunkcc776712015-02-17 20:18:47 -08001020 // Get current active client PIDs
1021 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1022 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001023
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -07001024 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1025 // address of PROCESS_STATE_NONEXISTENT as a reference argument
1026 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1027 // not have an out-of-class definition.
1028 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001029
Ruben Brunkcc776712015-02-17 20:18:47 -08001030 // Get priorites of all active PIDs
1031 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1032 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001033
Ruben Brunkcc776712015-02-17 20:18:47 -08001034 // Update all active clients' priorities
1035 std::map<int,int> pidToPriorityMap;
1036 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1037 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1038 }
1039 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001040
Ruben Brunkcc776712015-02-17 20:18:47 -08001041 // Get state for the given cameraId
1042 auto state = getCameraState(cameraId);
1043 if (state == nullptr) {
1044 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1045 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001046 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001047 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001048
1049 // Make descriptor for incoming client
1050 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1051 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1052 state->getConflicting(),
1053 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1054
1055 // Find clients that would be evicted
1056 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1057
1058 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1059 // background, so we cannot do evictions
1060 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1061 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1062 " priority).", clientPid);
1063
1064 sp<BasicClient> clientSp = clientDescriptor->getValue();
1065 String8 curTime = getFormattedCurrentTime();
1066 auto incompatibleClients =
1067 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1068
1069 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001070 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001071 cameraId.string(), packageName.string(), clientPid,
1072 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1073
1074 for (auto& i : incompatibleClients) {
1075 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1076 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1077 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1078 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001079 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1080 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1081 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1082 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001083 }
1084
1085 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001086 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001087 mEventLog.add(msg);
1088
1089 return -EBUSY;
1090 }
1091
1092 for (auto& i : evicted) {
1093 sp<BasicClient> clientSp = i->getValue();
1094 if (clientSp.get() == nullptr) {
1095 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1096
1097 // TODO: Remove this
1098 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1099 __FUNCTION__);
1100 mActiveClientManager.remove(i);
1101 continue;
1102 }
1103
1104 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1105 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001106 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001107
Ruben Brunkcc776712015-02-17 20:18:47 -08001108 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001109 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1110 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1111 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001112 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1113 i->getOwnerId(), i->getPriority(), cameraId.string(),
1114 packageName.string(), clientPid,
1115 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1116
1117 // Notify the client of disconnection
1118 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1119 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001120 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001121 }
1122
Ruben Brunkcc776712015-02-17 20:18:47 -08001123 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1124 // other clients from connecting in mServiceLockWrapper if held
1125 mServiceLock.unlock();
1126
1127 // Clear caller identity temporarily so client disconnect PID checks work correctly
1128 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1129
1130 // Destroy evicted clients
1131 for (auto& i : evictedClients) {
1132 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001133 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001135
1136 IPCThreadState::self()->restoreCallingIdentity(token);
1137
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001138 for (const auto& i : evictedClients) {
1139 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1140 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1141 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1142 if (ret == TIMED_OUT) {
1143 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1144 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1145 mActiveClientManager.toString().string());
1146 return -EBUSY;
1147 }
1148 if (ret != NO_ERROR) {
1149 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1150 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1151 ret, mActiveClientManager.toString().string());
1152 return ret;
1153 }
1154 }
1155
1156 evictedClients.clear();
1157
Ruben Brunkcc776712015-02-17 20:18:47 -08001158 // Once clients have been disconnected, relock
1159 mServiceLock.lock();
1160
1161 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1162 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1163 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001164 }
1165
Ruben Brunkcc776712015-02-17 20:18:47 -08001166 *partial = clientDescriptor;
1167 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001168}
1169
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001170status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001171 const sp<ICameraClient>& cameraClient,
1172 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001173 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001174 int clientUid,
1175 /*out*/
1176 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001177
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001178 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001179 status_t ret = NO_ERROR;
1180 String8 id = String8::format("%d", cameraId);
1181 sp<Client> client = nullptr;
1182 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001183 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001184
Ruben Brunkcc776712015-02-17 20:18:47 -08001185 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001186 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001187 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001188 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }
1190
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001191 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001192 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193}
1194
Zhijun Heb10cdad2014-06-16 16:38:35 -07001195status_t CameraService::connectLegacy(
1196 const sp<ICameraClient>& cameraClient,
1197 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001198 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001199 int clientUid,
1200 /*out*/
1201 sp<ICamera>& device) {
1202
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001203 ATRACE_CALL();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001204 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001205 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001206 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001207 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001208 /*
1209 * Either the HAL version is unspecified in which case this just creates
1210 * a camera client selected by the latest device version, or
1211 * it's a particular version in which case the HAL must supported
1212 * the open_legacy call
1213 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001214 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001215 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001216 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001217 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001218 return INVALID_OPERATION;
1219 }
1220
Ruben Brunkcc776712015-02-17 20:18:47 -08001221 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001222 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001223 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001224 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001225
Ruben Brunkcc776712015-02-17 20:18:47 -08001226 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001227 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001228 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001229 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001230 }
1231
Zhijun Heb10cdad2014-06-16 16:38:35 -07001232 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001234}
1235
Ruben Brunkcc776712015-02-17 20:18:47 -08001236status_t CameraService::connectDevice(
1237 const sp<ICameraDeviceCallbacks>& cameraCb,
1238 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001239 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001240 int clientUid,
1241 /*out*/
1242 sp<ICameraDeviceUser>& device) {
1243
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001244 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001245 status_t ret = NO_ERROR;
1246 String8 id = String8::format("%d", cameraId);
1247 sp<CameraDeviceClient> client = nullptr;
1248 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001249 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001250 /*out*/client);
1251
1252 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001253 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001254 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001255 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001256 }
1257
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 device = client;
1259 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001260}
1261
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001262status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1263 const sp<IBinder>& clientBinder) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001264
1265 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001266 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001267 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001268 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001269 }
1270
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001271 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001272 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001273
1274 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001275 auto state = getCameraState(id);
1276 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001277 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001278 return -EINVAL;
1279 }
1280
1281 ICameraServiceListener::Status cameraStatus = state->getStatus();
1282 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1283 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001284 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001285 return -EINVAL;
1286 }
1287
1288 {
1289 Mutex::Autolock al(mTorchStatusMutex);
1290 ICameraServiceListener::TorchStatus status;
1291 status_t res = getTorchStatusLocked(id, &status);
1292 if (res) {
1293 ALOGE("%s: getting current torch status failed for camera %s",
1294 __FUNCTION__, id.string());
1295 return -EINVAL;
1296 }
1297
1298 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001300 ALOGE("%s: torch mode of camera %s is not available because "
1301 "camera is in use", __FUNCTION__, id.string());
1302 return -EBUSY;
1303 } else {
1304 ALOGE("%s: torch mode of camera %s is not available due to "
1305 "insufficient resources", __FUNCTION__, id.string());
1306 return -EUSERS;
1307 }
1308 }
1309 }
1310
Ruben Brunk99e69712015-05-26 17:25:07 -07001311 {
1312 // Update UID map - this is used in the torch status changed callbacks, so must be done
1313 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001314 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001315 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1316 mTorchUidMap[id].first = uid;
1317 mTorchUidMap[id].second = uid;
1318 } else {
1319 // Set the pending UID
1320 mTorchUidMap[id].first = uid;
1321 }
1322 }
1323
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001324 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001325
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001326 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001327 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1328 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001329 return res;
1330 }
1331
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001332 {
1333 // update the link to client's death
1334 Mutex::Autolock al(mTorchClientMapMutex);
1335 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001336 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001337 if (enabled) {
1338 if (index == NAME_NOT_FOUND) {
1339 mTorchClientMap.add(id, clientBinder);
1340 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001341 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001342 mTorchClientMap.replaceValueAt(index, clientBinder);
1343 }
1344 clientBinder->linkToDeath(this);
1345 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001346 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001347 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001348 }
1349
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001350 return OK;
1351}
1352
Ruben Brunk6267b532015-04-30 17:44:07 -07001353void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001354 ATRACE_CALL();
1355
Ruben Brunk36597b22015-03-20 22:15:57 -07001356 switch(eventId) {
1357 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001358 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001359 break;
1360 }
1361 case ICameraService::NO_EVENT:
1362 default: {
1363 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1364 eventId);
1365 break;
1366 }
1367 }
1368}
1369
Ruben Brunk99e69712015-05-26 17:25:07 -07001370status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001371 ATRACE_CALL();
1372
Igor Murashkinbfc99152013-02-27 12:55:20 -08001373 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001374
Ruben Brunk3450ba72015-06-16 11:00:37 -07001375 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001376 ALOGE("%s: Listener must not be null", __FUNCTION__);
1377 return BAD_VALUE;
1378 }
1379
Igor Murashkinbfc99152013-02-27 12:55:20 -08001380 Mutex::Autolock lock(mServiceLock);
1381
Ruben Brunkcc776712015-02-17 20:18:47 -08001382 {
1383 Mutex::Autolock lock(mStatusListenerLock);
1384 for (auto& it : mListenerList) {
1385 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1386 ALOGW("%s: Tried to add listener %p which was already subscribed",
1387 __FUNCTION__, listener.get());
1388 return ALREADY_EXISTS;
1389 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001390 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001391
1392 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001393 }
1394
Igor Murashkinbfc99152013-02-27 12:55:20 -08001395
Igor Murashkincba2c162013-03-20 15:56:31 -07001396 /* Immediately signal current status to this listener only */
1397 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001398 Mutex::Autolock lock(mCameraStatesLock);
1399 for (auto& i : mCameraStates) {
1400 // TODO: Update binder to use String16 for camera IDs and remove;
1401 int id = cameraIdToInt(i.first);
1402 if (id == -1) continue;
1403
1404 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001405 }
1406 }
1407
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001408 /* Immediately signal current torch status to this listener only */
1409 {
1410 Mutex::Autolock al(mTorchStatusMutex);
1411 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001412 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1413 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001414 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001415 }
1416
Igor Murashkinbfc99152013-02-27 12:55:20 -08001417 return OK;
1418}
Ruben Brunkcc776712015-02-17 20:18:47 -08001419
1420status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001421 ATRACE_CALL();
1422
Igor Murashkinbfc99152013-02-27 12:55:20 -08001423 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1424
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001425 if (listener == 0) {
1426 ALOGE("%s: Listener must not be null", __FUNCTION__);
1427 return BAD_VALUE;
1428 }
1429
Igor Murashkinbfc99152013-02-27 12:55:20 -08001430 Mutex::Autolock lock(mServiceLock);
1431
Ruben Brunkcc776712015-02-17 20:18:47 -08001432 {
1433 Mutex::Autolock lock(mStatusListenerLock);
1434 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1435 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1436 mListenerList.erase(it);
1437 return OK;
1438 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001439 }
1440 }
1441
1442 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1443 __FUNCTION__, listener.get());
1444
1445 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001446}
1447
Ruben Brunkcc776712015-02-17 20:18:47 -08001448status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001449
1450 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001451 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1452
1453 if (parameters == NULL) {
1454 ALOGE("%s: parameters must not be null", __FUNCTION__);
1455 return BAD_VALUE;
1456 }
1457
1458 status_t ret = 0;
1459
1460 CameraParameters shimParams;
1461 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1462 // Error logged by caller
1463 return ret;
1464 }
1465
1466 String8 shimParamsString8 = shimParams.flatten();
1467 String16 shimParamsString16 = String16(shimParamsString8);
1468
1469 *parameters = shimParamsString16;
1470
1471 return OK;
1472}
1473
1474status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001475 ATRACE_CALL();
1476
Igor Murashkin65d14b92014-06-17 12:03:20 -07001477 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1478
1479 switch (apiVersion) {
1480 case API_VERSION_1:
1481 case API_VERSION_2:
1482 break;
1483 default:
1484 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1485 return BAD_VALUE;
1486 }
1487
1488 int facing = -1;
1489 int deviceVersion = getDeviceVersion(cameraId, &facing);
1490
1491 switch(deviceVersion) {
1492 case CAMERA_DEVICE_API_VERSION_1_0:
1493 case CAMERA_DEVICE_API_VERSION_2_0:
1494 case CAMERA_DEVICE_API_VERSION_2_1:
1495 case CAMERA_DEVICE_API_VERSION_3_0:
1496 case CAMERA_DEVICE_API_VERSION_3_1:
1497 if (apiVersion == API_VERSION_2) {
1498 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1499 __FUNCTION__, cameraId);
1500 return -EOPNOTSUPP;
1501 } else { // if (apiVersion == API_VERSION_1) {
1502 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1503 __FUNCTION__, cameraId);
1504 return OK;
1505 }
1506 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001507 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001508 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1509 __FUNCTION__, cameraId);
1510 return OK;
1511 case -1:
1512 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1513 return BAD_VALUE;
1514 default:
1515 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1516 return INVALID_OPERATION;
1517 }
1518
1519 return OK;
1520}
1521
Ruben Brunkcc776712015-02-17 20:18:47 -08001522void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001523 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 for (auto& i : mActiveClientManager.getAll()) {
1525 auto clientSp = i->getValue();
1526 if (clientSp.get() == client) {
1527 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001528 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001529 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001530}
1531
Ruben Brunkcc776712015-02-17 20:18:47 -08001532bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1533 const int callingPid = getCallingPid();
1534 const int servicePid = getpid();
1535 bool ret = false;
1536 {
1537 // Acquire mServiceLock and prevent other clients from connecting
1538 std::unique_ptr<AutoConditionLock> lock =
1539 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001540
Igor Murashkin634a5152013-02-20 17:15:11 -08001541
Ruben Brunkcc776712015-02-17 20:18:47 -08001542 std::vector<sp<BasicClient>> evicted;
1543 for (auto& i : mActiveClientManager.getAll()) {
1544 auto clientSp = i->getValue();
1545 if (clientSp.get() == nullptr) {
1546 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1547 mActiveClientManager.remove(i);
1548 continue;
1549 }
1550 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1551 callingPid == clientSp->getClientPid())) {
1552 mActiveClientManager.remove(i);
1553 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001554
Ruben Brunkcc776712015-02-17 20:18:47 -08001555 // Notify the client of disconnection
1556 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1557 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001558 }
1559 }
1560
Ruben Brunkcc776712015-02-17 20:18:47 -08001561 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1562 // other clients from connecting in mServiceLockWrapper if held
1563 mServiceLock.unlock();
1564
Ruben Brunk36597b22015-03-20 22:15:57 -07001565 // Do not clear caller identity, remote caller should be client proccess
1566
Ruben Brunkcc776712015-02-17 20:18:47 -08001567 for (auto& i : evicted) {
1568 if (i.get() != nullptr) {
1569 i->disconnect();
1570 ret = true;
1571 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001572 }
1573
Ruben Brunkcc776712015-02-17 20:18:47 -08001574 // Reacquire mServiceLock
1575 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001576
Ruben Brunkcc776712015-02-17 20:18:47 -08001577 } // lock is destroyed, allow further connect calls
1578
1579 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001580}
1581
Igor Murashkinecf17e82012-10-02 16:05:11 -07001582
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001583/**
1584 * Check camera capabilities, such as support for basic color operation
1585 */
1586int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1587
1588 // Assume all devices pre-v3.3 are backward-compatible
1589 bool isBackwardCompatible = true;
1590 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1591 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1592 isBackwardCompatible = false;
1593 status_t res;
1594 camera_metadata_ro_entry_t caps;
1595 res = find_camera_metadata_ro_entry(
1596 info.static_camera_characteristics,
1597 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1598 &caps);
1599 if (res != 0) {
1600 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1601 __FUNCTION__, id);
1602 caps.count = 0;
1603 }
1604 for (size_t i = 0; i < caps.count; i++) {
1605 if (caps.data.u8[i] ==
1606 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1607 isBackwardCompatible = true;
1608 break;
1609 }
1610 }
1611 }
1612
1613 if (!isBackwardCompatible) {
1614 mNumberOfNormalCameras--;
1615 *latestStrangeCameraId = id;
1616 } else {
1617 if (id > *latestStrangeCameraId) {
1618 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1619 "This is not allowed due backward-compatibility requirements",
1620 __FUNCTION__, id, *latestStrangeCameraId);
1621 logServiceError("Invalid order of camera devices", ENODEV);
1622 mNumberOfCameras = 0;
1623 mNumberOfNormalCameras = 0;
1624 return INVALID_OPERATION;
1625 }
1626 }
1627 return OK;
1628}
1629
Ruben Brunkcc776712015-02-17 20:18:47 -08001630std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1631 const String8& cameraId) const {
1632 std::shared_ptr<CameraState> state;
1633 {
1634 Mutex::Autolock lock(mCameraStatesLock);
1635 auto iter = mCameraStates.find(cameraId);
1636 if (iter != mCameraStates.end()) {
1637 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 }
1639 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001640 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641}
1642
Ruben Brunkcc776712015-02-17 20:18:47 -08001643sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1644 // Remove from active clients list
1645 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1646 if (clientDescriptorPtr == nullptr) {
1647 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1648 cameraId.string());
1649 return sp<BasicClient>{nullptr};
1650 }
1651
1652 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001653}
1654
Ruben Brunk6267b532015-04-30 17:44:07 -07001655void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001656 // Acquire mServiceLock and prevent other clients from connecting
1657 std::unique_ptr<AutoConditionLock> lock =
1658 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1659
Ruben Brunk6267b532015-04-30 17:44:07 -07001660 std::set<userid_t> newAllowedUsers;
1661 for (size_t i = 0; i < length; i++) {
1662 if (newUserId[i] < 0) {
1663 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1664 __FUNCTION__, newUserId[i]);
1665 return;
1666 }
1667 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001668 }
1669
Ruben Brunka8ca9152015-04-07 14:23:40 -07001670
Ruben Brunk6267b532015-04-30 17:44:07 -07001671 if (newAllowedUsers == mAllowedUsers) {
1672 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1673 return;
1674 }
1675
1676 logUserSwitch(mAllowedUsers, newAllowedUsers);
1677
1678 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001679
1680 // Current user has switched, evict all current clients.
1681 std::vector<sp<BasicClient>> evicted;
1682 for (auto& i : mActiveClientManager.getAll()) {
1683 auto clientSp = i->getValue();
1684
1685 if (clientSp.get() == nullptr) {
1686 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1687 continue;
1688 }
1689
Ruben Brunk6267b532015-04-30 17:44:07 -07001690 // Don't evict clients that are still allowed.
1691 uid_t clientUid = clientSp->getClientUid();
1692 userid_t clientUserId = multiuser_get_user_id(clientUid);
1693 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1694 continue;
1695 }
1696
Ruben Brunk36597b22015-03-20 22:15:57 -07001697 evicted.push_back(clientSp);
1698
1699 String8 curTime = getFormattedCurrentTime();
1700
1701 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1702 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001703
Ruben Brunk36597b22015-03-20 22:15:57 -07001704 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001705 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001706 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001707 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1708 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001709
1710 }
1711
1712 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1713 // blocking other clients from connecting in mServiceLockWrapper if held.
1714 mServiceLock.unlock();
1715
1716 // Clear caller identity temporarily so client disconnect PID checks work correctly
1717 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1718
1719 for (auto& i : evicted) {
1720 i->disconnect();
1721 }
1722
1723 IPCThreadState::self()->restoreCallingIdentity(token);
1724
1725 // Reacquire mServiceLock
1726 mServiceLock.lock();
1727}
Ruben Brunkcc776712015-02-17 20:18:47 -08001728
Ruben Brunka8ca9152015-04-07 14:23:40 -07001729void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001730 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001731 Mutex::Autolock l(mLogLock);
1732 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733}
1734
Ruben Brunka8ca9152015-04-07 14:23:40 -07001735void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001736 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001737 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001738 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001739 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001740}
1741
1742void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001743 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001744 // Log the clients evicted
1745 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001746 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001747}
1748
1749void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001750 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001751 // Log the client rejected
1752 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001753 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001754}
1755
Ruben Brunk6267b532015-04-30 17:44:07 -07001756void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1757 const std::set<userid_t>& newUserIds) {
1758 String8 newUsers = toString(newUserIds);
1759 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001760 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001761 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1762 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001763}
1764
1765void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1766 // Log the device removal
1767 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1768}
1769
1770void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1771 // Log the device removal
1772 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1773}
1774
1775void CameraService::logClientDied(int clientPid, const char* reason) {
1776 // Log the device removal
1777 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001778}
1779
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001780void CameraService::logServiceError(const char* msg, int errorCode) {
1781 String8 curTime = getFormattedCurrentTime();
1782 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1783}
1784
Ruben Brunk36597b22015-03-20 22:15:57 -07001785status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1786 uint32_t flags) {
1787
1788 const int pid = getCallingPid();
1789 const int selfPid = getpid();
1790
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 // Permission checks
1792 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001793 case BnCameraService::CONNECT:
1794 case BnCameraService::CONNECT_DEVICE:
1795 case BnCameraService::CONNECT_LEGACY: {
1796 if (pid != selfPid) {
1797 // we're called from a different process, do the real check
1798 if (!checkCallingPermission(
1799 String16("android.permission.CAMERA"))) {
1800 const int uid = getCallingUid();
1801 ALOGE("Permission Denial: "
1802 "can't use the camera pid=%d, uid=%d", pid, uid);
1803 return PERMISSION_DENIED;
1804 }
1805 }
1806 break;
1807 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001808 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1809 if (pid != selfPid) {
1810 // Ensure we're being called by system_server, or similar process with
1811 // permissions to notify the camera service about system events
1812 if (!checkCallingPermission(
1813 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1814 const int uid = getCallingUid();
1815 ALOGE("Permission Denial: cannot send updates to camera service about system"
1816 " events from pid=%d, uid=%d", pid, uid);
1817 return PERMISSION_DENIED;
1818 }
1819 }
1820 break;
1821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 }
1823
1824 return BnCameraService::onTransact(code, data, reply, flags);
1825}
1826
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827// We share the media players for shutter and recording sound for all clients.
1828// A reference count is kept to determine when we will actually release the
1829// media players.
1830
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001831MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001833 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001834 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 mp->prepare();
1836 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001837 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 return NULL;
1839 }
1840 return mp;
1841}
1842
1843void CameraService::loadSound() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001844 ATRACE_CALL();
1845
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 Mutex::Autolock lock(mSoundLock);
1847 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1848 if (mSoundRef++) return;
1849
1850 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
Chien-Yu Chen82104eb2015-10-14 11:29:31 -07001851 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1852 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853}
1854
1855void CameraService::releaseSound() {
1856 Mutex::Autolock lock(mSoundLock);
1857 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1858 if (--mSoundRef) return;
1859
1860 for (int i = 0; i < NUM_SOUNDS; i++) {
1861 if (mSoundPlayer[i] != 0) {
1862 mSoundPlayer[i]->disconnect();
1863 mSoundPlayer[i].clear();
1864 }
1865 }
1866}
1867
1868void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001869 ATRACE_CALL();
1870
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 LOG1("playSound(%d)", kind);
1872 Mutex::Autolock lock(mSoundLock);
1873 sp<MediaPlayer> player = mSoundPlayer[kind];
1874 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001875 player->seekTo(0);
1876 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 }
1878}
1879
1880// ----------------------------------------------------------------------------
1881
1882CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001883 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001884 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001885 int cameraId, int cameraFacing,
1886 int clientPid, uid_t clientUid,
1887 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001888 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001889 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001890 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001891 cameraId, cameraFacing,
1892 clientPid, clientUid,
1893 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001894{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001896 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001898 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001901
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001902 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903}
1904
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905// tear down the client
1906CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001907 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001908 mDestructionStarted = true;
1909
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001910 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001911 // unconditionally disconnect. function is idempotent
1912 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913}
1914
Igor Murashkin634a5152013-02-20 17:15:11 -08001915CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001916 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001917 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001918 int cameraId, int cameraFacing,
1919 int clientPid, uid_t clientUid,
1920 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001921 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001922{
1923 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001924 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001925 mCameraId = cameraId;
1926 mCameraFacing = cameraFacing;
1927 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001928 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001929 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001930 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001931 mDestructionStarted = false;
1932}
1933
1934CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001935 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001936 mDestructionStarted = true;
1937}
1938
1939void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001940 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001941 return;
1942 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001943 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001944
1945 mCameraService->removeByClient(this);
1946 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001947 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001948
1949 sp<IBinder> remote = getRemote();
1950 if (remote != nullptr) {
1951 remote->unlinkToDeath(mCameraService);
1952 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001953
1954 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001955 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1956
Igor Murashkincba2c162013-03-20 15:56:31 -07001957 // client shouldn't be able to call into us anymore
1958 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001959}
1960
Ruben Brunkcc776712015-02-17 20:18:47 -08001961String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001962 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001963}
1964
1965
1966int CameraService::BasicClient::getClientPid() const {
1967 return mClientPid;
1968}
1969
Ruben Brunk6267b532015-04-30 17:44:07 -07001970uid_t CameraService::BasicClient::getClientUid() const {
1971 return mClientUid;
1972}
1973
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001974bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1975 // Defaults to API2.
1976 return level == API_2;
1977}
1978
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001979status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001980 ATRACE_CALL();
1981
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001982 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001983 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001984 mOpsCallback = new OpsCallback(this);
1985
Igor Murashkine6800ce2013-03-04 17:25:57 -08001986 {
1987 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001988 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001989 }
1990
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001991 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001992 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001993 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001994 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001995
Svetoslav28e8ef72015-05-11 19:21:31 -07001996 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001997 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001998 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001999 return PERMISSION_DENIED;
2000 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002001
Svetoslav28e8ef72015-05-11 19:21:31 -07002002 if (res == AppOpsManager::MODE_IGNORED) {
2003 ALOGI("Camera %d: Access for \"%s\" has been restricted",
2004 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002005 // Return the same error as for device policy manager rejection
2006 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002007 }
2008
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002009 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002010
2011 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2012 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08002013 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002014
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002015 // Transition device state to OPEN
2016 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2017 String8::format("%d", mCameraId));
2018
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002019 return OK;
2020}
2021
2022status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002023 ATRACE_CALL();
2024
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002025 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002026 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002027 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002028 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002029 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002030 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002031
Ruben Brunkcc776712015-02-17 20:18:47 -08002032 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2033 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002034
Ruben Brunkcc776712015-02-17 20:18:47 -08002035 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002036 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08002037 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002038
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002039 // Transition device state to CLOSED
2040 mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2041 String8::format("%d", mCameraId));
2042
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002043 // Notify flashlight that a camera device is closed.
2044 mCameraService->mFlashlight->deviceClosed(
2045 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002046 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002047 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002048 if (mOpsCallback != NULL) {
2049 mAppOpsManager.stopWatchingMode(mOpsCallback);
2050 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002051 mOpsCallback.clear();
2052
2053 return OK;
2054}
2055
2056void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002057 ATRACE_CALL();
2058
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002059 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002060 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002061
2062 if (op != AppOpsManager::OP_CAMERA) {
2063 ALOGW("Unexpected app ops notification received: %d", op);
2064 return;
2065 }
2066
2067 int32_t res;
2068 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002069 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002070 ALOGV("checkOp returns: %d, %s ", res,
2071 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2072 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2073 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2074 "UNKNOWN");
2075
2076 if (res != AppOpsManager::MODE_ALLOWED) {
2077 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2078 myName.string());
2079 // Reset the client PID to allow server-initiated disconnect,
2080 // and to prevent further calls by client.
2081 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002082 CaptureResultExtras resultExtras; // a dummy result (invalid)
2083 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002084 disconnect();
2085 }
2086}
2087
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088// ----------------------------------------------------------------------------
2089
Ruben Brunkcc776712015-02-17 20:18:47 -08002090// Provide client strong pointer for callbacks.
2091sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2092 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2093 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2094 if (clientDescriptor != nullptr) {
2095 return sp<Client>{
2096 static_cast<Client*>(clientDescriptor->getValue().get())};
2097 }
2098 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099}
2100
Jianing Weicb0652e2014-03-12 18:29:36 -07002101void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2102 const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002103 if (mRemoteCallback != NULL) {
2104 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2105 } else {
2106 ALOGE("mRemoteCallback is NULL!!");
2107 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002108}
2109
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002110// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002111void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002112 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002113 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002114}
2115
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002116bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2117 return level == API_1;
2118}
2119
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002120CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2121 mClient(client) {
2122}
2123
2124void CameraService::Client::OpsCallback::opChanged(int32_t op,
2125 const String16& packageName) {
2126 sp<BasicClient> client = mClient.promote();
2127 if (client != NULL) {
2128 client->opChanged(op, packageName);
2129 }
2130}
2131
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002133// CameraState
2134// ----------------------------------------------------------------------------
2135
2136CameraService::CameraState::CameraState(const String8& id, int cost,
2137 const std::set<String8>& conflicting) : mId(id),
2138 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2139
2140CameraService::CameraState::~CameraState() {}
2141
2142ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2143 Mutex::Autolock lock(mStatusLock);
2144 return mStatus;
2145}
2146
2147CameraParameters CameraService::CameraState::getShimParams() const {
2148 return mShimParams;
2149}
2150
2151void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2152 mShimParams = params;
2153}
2154
2155int CameraService::CameraState::getCost() const {
2156 return mCost;
2157}
2158
2159std::set<String8> CameraService::CameraState::getConflicting() const {
2160 return mConflicting;
2161}
2162
2163String8 CameraService::CameraState::getId() const {
2164 return mId;
2165}
2166
2167// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002168// ClientEventListener
2169// ----------------------------------------------------------------------------
2170
2171void CameraService::ClientEventListener::onClientAdded(
2172 const resource_policy::ClientDescriptor<String8,
2173 sp<CameraService::BasicClient>>& descriptor) {
2174 auto basicClient = descriptor.getValue();
2175 if (basicClient.get() != nullptr) {
2176 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2177 notifier.noteStartCamera(descriptor.getKey(),
2178 static_cast<int>(basicClient->getClientUid()));
2179 }
2180}
2181
2182void CameraService::ClientEventListener::onClientRemoved(
2183 const resource_policy::ClientDescriptor<String8,
2184 sp<CameraService::BasicClient>>& descriptor) {
2185 auto basicClient = descriptor.getValue();
2186 if (basicClient.get() != nullptr) {
2187 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2188 notifier.noteStopCamera(descriptor.getKey(),
2189 static_cast<int>(basicClient->getClientUid()));
2190 }
2191}
2192
2193
2194// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002195// CameraClientManager
2196// ----------------------------------------------------------------------------
2197
Ruben Brunk99e69712015-05-26 17:25:07 -07002198CameraService::CameraClientManager::CameraClientManager() {
2199 setListener(std::make_shared<ClientEventListener>());
2200}
2201
Ruben Brunkcc776712015-02-17 20:18:47 -08002202CameraService::CameraClientManager::~CameraClientManager() {}
2203
2204sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2205 const String8& id) const {
2206 auto descriptor = get(id);
2207 if (descriptor == nullptr) {
2208 return sp<BasicClient>{nullptr};
2209 }
2210 return descriptor->getValue();
2211}
2212
2213String8 CameraService::CameraClientManager::toString() const {
2214 auto all = getAll();
2215 String8 ret("[");
2216 bool hasAny = false;
2217 for (auto& i : all) {
2218 hasAny = true;
2219 String8 key = i->getKey();
2220 int32_t cost = i->getCost();
2221 int32_t pid = i->getOwnerId();
2222 int32_t priority = i->getPriority();
2223 auto conflicting = i->getConflicting();
2224 auto clientSp = i->getValue();
2225 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002226 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002227 if (clientSp.get() != nullptr) {
2228 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002229 uid_t clientUid = clientSp->getClientUid();
2230 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002231 }
2232 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2233 PRId32 ", ", key.string(), cost, pid, priority);
2234
Ruben Brunk6267b532015-04-30 17:44:07 -07002235 if (clientSp.get() != nullptr) {
2236 ret.appendFormat("User Id: %d, ", clientUserId);
2237 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002238 if (packageName.size() != 0) {
2239 ret.appendFormat("Client Package Name: %s", packageName.string());
2240 }
2241
2242 ret.append(", Conflicting Client Devices: {");
2243 for (auto& j : conflicting) {
2244 ret.appendFormat("%s, ", j.string());
2245 }
2246 ret.append("})");
2247 }
2248 if (hasAny) ret.append("\n");
2249 ret.append("]\n");
2250 return ret;
2251}
2252
2253CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2254 const String8& key, const sp<BasicClient>& value, int32_t cost,
2255 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2256
2257 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2258 key, value, cost, conflictingKeys, priority, ownerId);
2259}
2260
2261CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2262 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2263 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2264 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2265}
2266
2267// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268
2269static const int kDumpLockRetries = 50;
2270static const int kDumpLockSleep = 60000;
2271
2272static bool tryLock(Mutex& mutex)
2273{
2274 bool locked = false;
2275 for (int i = 0; i < kDumpLockRetries; ++i) {
2276 if (mutex.tryLock() == NO_ERROR) {
2277 locked = true;
2278 break;
2279 }
2280 usleep(kDumpLockSleep);
2281 }
2282 return locked;
2283}
2284
2285status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002286 ATRACE_CALL();
2287
Ruben Brunka8ca9152015-04-07 14:23:40 -07002288 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dcashmanfefa6142015-09-09 13:43:01 -07002290 result = result.format("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291 "can't dump CameraService from pid=%d, uid=%d\n",
2292 getCallingPid(),
2293 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294 write(fd, result.string(), result.size());
2295 } else {
2296 bool locked = tryLock(mServiceLock);
2297 // failed to lock - CameraService is probably deadlocked
2298 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002299 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002300 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301 }
2302
2303 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002304 if (!mModule) {
2305 result = String8::format("No camera module available!\n");
2306 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002307
2308 // Dump event log for error information
2309 dumpEventLog(fd);
2310
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002311 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002312 return NO_ERROR;
2313 }
2314
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002315 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2316 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2317 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2318 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002319 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2320 String8 activeClientString = mActiveClientManager.toString();
2321 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002322 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002323
Ruben Brunkf81648e2014-04-17 16:14:57 -07002324 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2325 if (desc == NULL) {
2326 result.appendFormat("Vendor tags left unimplemented.\n");
2327 } else {
2328 result.appendFormat("Vendor tag definitions:\n");
2329 }
2330
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002331 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002332
2333 if (desc != NULL) {
2334 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2335 }
2336
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002337 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002338
2339 bool stateLocked = tryLock(mCameraStatesLock);
2340 if (!stateLocked) {
2341 result = String8::format("CameraStates in use, may be deadlocked\n");
2342 write(fd, result.string(), result.size());
2343 }
2344
2345 for (auto& state : mCameraStates) {
2346 String8 cameraId = state.first;
2347 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002348 camera_info info;
2349
Ruben Brunkcc776712015-02-17 20:18:47 -08002350 // TODO: Change getCameraInfo + HAL to use String cameraIds
2351 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002352 if (rc != OK) {
2353 result.appendFormat(" Error reading static information!\n");
2354 write(fd, result.string(), result.size());
2355 } else {
2356 result.appendFormat(" Facing: %s\n",
2357 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2358 result.appendFormat(" Orientation: %d\n", info.orientation);
2359 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002360 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002361 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2362 } else {
2363 deviceVersion = info.device_version;
2364 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002365
2366 auto conflicting = state.second->getConflicting();
2367 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2368 result.appendFormat(" Conflicting Devices:");
2369 for (auto& id : conflicting) {
2370 result.appendFormat(" %s", cameraId.string());
2371 }
2372 if (conflicting.size() == 0) {
2373 result.appendFormat(" NONE");
2374 }
2375 result.appendFormat("\n");
2376
2377 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002378 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2379 result.appendFormat(" Device static metadata:\n");
2380 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002381 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002382 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002383 } else {
2384 write(fd, result.string(), result.size());
2385 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002386
2387 CameraParameters p = state.second->getShimParams();
2388 if (!p.isEmpty()) {
2389 result = String8::format(" Camera1 API shim is using parameters:\n ");
2390 write(fd, result.string(), result.size());
2391 p.dump(fd, args);
2392 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002393 }
2394
Ruben Brunkcc776712015-02-17 20:18:47 -08002395 auto clientDescriptor = mActiveClientManager.get(cameraId);
2396 if (clientDescriptor == nullptr) {
2397 result = String8::format(" Device %s is closed, no client instance\n",
2398 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002399 write(fd, result.string(), result.size());
2400 continue;
2401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002402 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002403 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2404 cameraId.string());
2405 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2406 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2407
2408 auto client = clientDescriptor->getValue();
2409 result.appendFormat("Client package: %s\n",
2410 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002411 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002412
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002413 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002415
2416 if (stateLocked) mCameraStatesLock.unlock();
2417
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002419 result = String8::format("\nNo active camera clients yet.\n");
2420 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 }
2422
2423 if (locked) mServiceLock.unlock();
2424
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002425 // Dump camera traces if there were any
2426 write(fd, "\n", 1);
2427 camera3::CameraTraces::dump(fd, args);
2428
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 // change logging level
2430 int n = args.size();
2431 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002432 String16 verboseOption("-v");
2433 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 String8 levelStr(args[i+1]);
2435 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002436 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002438 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 }
2440 }
2441 }
2442 return NO_ERROR;
2443}
2444
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002445void CameraService::dumpEventLog(int fd) {
2446 String8 result = String8("\nPrior client events (most recent at top):\n");
2447
2448 Mutex::Autolock l(mLogLock);
2449 for (const auto& msg : mEventLog) {
2450 result.appendFormat(" %s\n", msg.string());
2451 }
2452
2453 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2454 result.append(" ...\n");
2455 } else if (mEventLog.size() == 0) {
2456 result.append(" [no events yet]\n");
2457 }
2458 result.append("\n");
2459
2460 write(fd, result.string(), result.size());
2461}
2462
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002463void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002464 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002465 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2466 if (mTorchClientMap[i] == who) {
2467 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002468 String8 cameraId = mTorchClientMap.keyAt(i);
2469 status_t res = mFlashlight->setTorchMode(cameraId, false);
2470 if (res) {
2471 ALOGE("%s: torch client died but couldn't turn off torch: "
2472 "%s (%d)", __FUNCTION__, strerror(-res), res);
2473 return;
2474 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002475 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002476 break;
2477 }
2478 }
2479}
2480
Ruben Brunkcc776712015-02-17 20:18:47 -08002481/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002482
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002483 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002484 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2485 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002486 */
2487
Ruben Brunka8ca9152015-04-07 14:23:40 -07002488 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2489
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002490 // check torch client
2491 handleTorchClientBinderDied(who);
2492
2493 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002494 if(!evictClientIdByRemote(who)) {
2495 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002496 return;
2497 }
2498
Ruben Brunkcc776712015-02-17 20:18:47 -08002499 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2500 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002501}
2502
Ruben Brunkcc776712015-02-17 20:18:47 -08002503void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2504 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002505}
2506
Ruben Brunkcc776712015-02-17 20:18:47 -08002507void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2508 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2509 // Do not lock mServiceLock here or can get into a deadlock from
2510 // connect() -> disconnect -> updateStatus
2511
2512 auto state = getCameraState(cameraId);
2513
2514 if (state == nullptr) {
2515 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2516 cameraId.string());
2517 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002518 }
2519
Ruben Brunkcc776712015-02-17 20:18:47 -08002520 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2521 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2522 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2523 (const String8& cameraId, ICameraServiceListener::Status status) {
2524
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002525 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2526 // Update torch status if it has a flash unit.
2527 Mutex::Autolock al(mTorchStatusMutex);
2528 ICameraServiceListener::TorchStatus torchStatus;
2529 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2530 NAME_NOT_FOUND) {
2531 ICameraServiceListener::TorchStatus newTorchStatus =
2532 status == ICameraServiceListener::STATUS_PRESENT ?
2533 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2534 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2535 if (torchStatus != newTorchStatus) {
2536 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2537 }
2538 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002539 }
2540
2541 Mutex::Autolock lock(mStatusListenerLock);
2542
2543 for (auto& listener : mListenerList) {
2544 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2545 int id = cameraIdToInt(cameraId);
2546 if (id != -1) listener->onStatusChanged(status, id);
2547 }
2548 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002549}
2550
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002551void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2552 const String8& cameraId) {
2553 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2554 if (proxyBinder == nullptr) return;
2555 String16 id(cameraId);
2556 proxyBinder->notifyCameraState(id, newState);
2557}
2558
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002559status_t CameraService::getTorchStatusLocked(
2560 const String8& cameraId,
2561 ICameraServiceListener::TorchStatus *status) const {
2562 if (!status) {
2563 return BAD_VALUE;
2564 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002565 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2566 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002567 // invalid camera ID or the camera doesn't have a flash unit
2568 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002569 }
2570
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002571 *status = mTorchStatusMap.valueAt(index);
2572 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002573}
2574
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002575status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002576 ICameraServiceListener::TorchStatus status) {
2577 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2578 if (index == NAME_NOT_FOUND) {
2579 return BAD_VALUE;
2580 }
2581 ICameraServiceListener::TorchStatus& item =
2582 mTorchStatusMap.editValueAt(index);
2583 item = status;
2584
2585 return OK;
2586}
2587
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588}; // namespace android