blob: c43f66915bd827a96ea1962617dcb862533b6b3b [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Iliyan Malchev8951a972011-04-14 16:55:59 -070018//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070019
Ruben Brunkcc776712015-02-17 20:18:47 -080020#include <algorithm>
21#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070022#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080023#include <cstring>
24#include <ctime>
25#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070026#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080027#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <pthread.h>
29
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080030#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
33#include <binder/MemoryBase.h>
34#include <binder/MemoryHeapBase.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080035#include <binder/ProcessInfoService.h>
Ruben Brunk2823ce02015-05-19 17:25:13 -070036#include <camera/ICameraServiceProxy.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);
160 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
161 err = mModule->init();
162 if (err != OK) {
163 ALOGE("Could not initialize camera HAL module: %d (%s)", err,
164 strerror(-err));
165 logServiceError("Could not initialize camera HAL module", err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800166
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700167 mNumberOfCameras = 0;
168 delete mModule;
169 mModule = nullptr;
170 return;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700171 }
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
176 mFlashlight = new CameraFlashlight(*mModule, *this);
177 status_t res = mFlashlight->findFlashUnits();
178 if (res) {
179 // impossible because we haven't open any camera devices.
180 ALOGE("Failed to find flash units.");
181 }
182
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700183 int latestStrangeCameraId = INT_MAX;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700184 for (int i = 0; i < mNumberOfCameras; i++) {
185 String8 cameraId = String8::format("%d", i);
186
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700187 // Get camera info
188
189 struct camera_info info;
190 bool haveInfo = true;
191 status_t rc = mModule->getCameraInfo(i, &info);
192 if (rc != NO_ERROR) {
193 ALOGE("%s: Received error loading camera info for device %d, cost and"
194 " conflicting devices fields set to defaults for this device.",
195 __FUNCTION__, i);
196 haveInfo = false;
197 }
198
199 // Check for backwards-compatibility support
200 if (haveInfo) {
201 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
202 delete mModule;
203 mModule = nullptr;
204 return;
205 }
206 }
207
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700208 // Defaults to use for cost and conflicting devices
209 int cost = 100;
210 char** conflicting_devices = nullptr;
211 size_t conflicting_devices_length = 0;
212
213 // If using post-2.4 module version, query the cost + conflicting devices from the HAL
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700214 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
215 cost = info.resource_cost;
216 conflicting_devices = info.conflicting_devices;
217 conflicting_devices_length = info.conflicting_devices_length;
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700218 }
219
220 std::set<String8> conflicting;
221 for (size_t i = 0; i < conflicting_devices_length; i++) {
222 conflicting.emplace(String8(conflicting_devices[i]));
223 }
224
225 // Initialize state for each camera device
226 {
227 Mutex::Autolock lock(mCameraStatesLock);
228 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
229 conflicting));
230 }
231
232 if (mFlashlight->hasFlashUnit(cameraId)) {
233 mTorchStatusMap.add(cameraId,
234 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
235 }
236 }
237
238 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
239 mModule->setCallbacks(this);
240 }
241
242 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
243
244 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
245 setUpVendorTags();
246 }
247
248 CameraDeviceFactory::registerService(this);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700249
250 CameraService::pingCameraServiceProxy();
251}
252
253void CameraService::pingCameraServiceProxy() {
254 sp<IServiceManager> sm = defaultServiceManager();
255 sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
256 if (binder == nullptr) {
257 return;
258 }
259 sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
260 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700261}
262
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263CameraService::~CameraService() {
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800264 if (mModule) {
265 delete mModule;
Ruben Brunkcc776712015-02-17 20:18:47 -0800266 mModule = nullptr;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800267 }
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800268 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Ruben Brunkcc776712015-02-17 20:18:47 -0800269 gCameraService = nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700270}
271
Ruben Brunkcc776712015-02-17 20:18:47 -0800272void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
273 camera_device_status_t newStatus) {
274 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
Igor Murashkincba2c162013-03-20 15:56:31 -0700275 cameraId, newStatus);
276
Ruben Brunkcc776712015-02-17 20:18:47 -0800277 String8 id = String8::format("%d", cameraId);
278 std::shared_ptr<CameraState> state = getCameraState(id);
279
280 if (state == nullptr) {
Igor Murashkincba2c162013-03-20 15:56:31 -0700281 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
282 return;
283 }
284
Ruben Brunkcc776712015-02-17 20:18:47 -0800285 ICameraServiceListener::Status oldStatus = state->getStatus();
286
287 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
288 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700289 return;
290 }
291
Igor Murashkincba2c162013-03-20 15:56:31 -0700292 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700293 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
294 newStatus));
Ruben Brunkcc776712015-02-17 20:18:47 -0800295 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700296 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800297 // Don't do this in updateStatus to avoid deadlock over mServiceLock
298 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700299
Ruben Brunkcc776712015-02-17 20:18:47 -0800300 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
301 // to this device until the status changes
302 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700303
Ruben Brunkcc776712015-02-17 20:18:47 -0800304 // Remove cached shim parameters
305 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700306
Ruben Brunkcc776712015-02-17 20:18:47 -0800307 // Remove the client from the list of active clients
308 clientToDisconnect = removeClientLocked(id);
309
310 // Notify the client of disconnection
Tom Keel056c93e2015-10-08 16:42:56 +0200311 if (clientToDisconnect != nullptr) {
312 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
313 CaptureResultExtras{});
314 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700315 }
316
Ruben Brunkcc776712015-02-17 20:18:47 -0800317 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
318 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700319
Ruben Brunkcc776712015-02-17 20:18:47 -0800320 // Disconnect client
321 if (clientToDisconnect.get() != nullptr) {
322 // Ensure not in binder RPC so client disconnect PID checks work correctly
323 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
324 "onDeviceStatusChanged must be called from the camera service process!");
325 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700326 }
327
Ruben Brunkcc776712015-02-17 20:18:47 -0800328 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700329 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
330 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
331 newStatus));
332 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800333 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700334 }
335
Igor Murashkincba2c162013-03-20 15:56:31 -0700336}
337
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800338void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800339 ICameraServiceListener::TorchStatus newStatus) {
340 Mutex::Autolock al(mTorchStatusMutex);
341 onTorchStatusChangedLocked(cameraId, newStatus);
342}
343
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800344void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800345 ICameraServiceListener::TorchStatus newStatus) {
346 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
347 __FUNCTION__, cameraId.string(), newStatus);
348
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800349 ICameraServiceListener::TorchStatus status;
350 status_t res = getTorchStatusLocked(cameraId, &status);
351 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700352 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
353 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800354 return;
355 }
356 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800357 return;
358 }
359
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800360 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800361 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700362 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800363 return;
364 }
365
Ruben Brunkcc776712015-02-17 20:18:47 -0800366 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700367 // Update battery life logging for flashlight
368 Mutex::Autolock al(mTorchClientMapMutex);
369 auto iter = mTorchUidMap.find(cameraId);
370 if (iter != mTorchUidMap.end()) {
371 int oldUid = iter->second.second;
372 int newUid = iter->second.first;
373 BatteryNotifier& notifier(BatteryNotifier::getInstance());
374 if (oldUid != newUid) {
375 // If the UID has changed, log the status and update current UID in mTorchUidMap
376 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
377 notifier.noteFlashlightOff(cameraId, oldUid);
378 }
379 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
380 notifier.noteFlashlightOn(cameraId, newUid);
381 }
382 iter->second.second = newUid;
383 } else {
384 // If the UID has not changed, log the status
385 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
386 notifier.noteFlashlightOn(cameraId, oldUid);
387 } else {
388 notifier.noteFlashlightOff(cameraId, oldUid);
389 }
390 }
391 }
392 }
393
394 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800395 Mutex::Autolock lock(mStatusListenerLock);
396 for (auto& i : mListenerList) {
397 i->onTorchStatusChanged(newStatus, String16{cameraId});
398 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800399 }
400}
401
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700403 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
404}
405
406int32_t CameraService::getNumberOfCameras(int type) {
407 switch (type) {
408 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
409 return mNumberOfNormalCameras;
410 case CAMERA_TYPE_ALL:
411 return mNumberOfCameras;
412 default:
413 ALOGW("%s: Unknown camera type %d, returning 0",
414 __FUNCTION__, type);
415 return 0;
416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417}
418
419status_t CameraService::getCameraInfo(int cameraId,
420 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700421 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700422 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700423 }
424
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
426 return BAD_VALUE;
427 }
428
Iliyan Malchev8951a972011-04-14 16:55:59 -0700429 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700430 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800431 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700432 cameraInfo->facing = info.facing;
433 cameraInfo->orientation = info.orientation;
434 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435}
436
Ruben Brunkcc776712015-02-17 20:18:47 -0800437int CameraService::cameraIdToInt(const String8& cameraId) {
438 errno = 0;
439 size_t pos = 0;
440 int ret = stoi(std::string{cameraId.string()}, &pos);
441 if (errno != 0 || pos != cameraId.size()) {
442 return -1;
443 }
444 return ret;
445}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700446
447status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
448 status_t ret = OK;
449 struct CameraInfo info;
450 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
451 return ret;
452 }
453
454 CameraMetadata shimInfo;
455 int32_t orientation = static_cast<int32_t>(info.orientation);
456 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
457 return ret;
458 }
459
460 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
461 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
462 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
463 return ret;
464 }
465
Igor Murashkin65d14b92014-06-17 12:03:20 -0700466 CameraParameters shimParams;
467 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
468 // Error logged by callee
469 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700470 }
471
472 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700473 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700474 Vector<int32_t> formats;
475 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700476 {
477 shimParams.getSupportedPreviewSizes(/*out*/sizes);
478 shimParams.getSupportedPreviewFormats(/*out*/formats);
479 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700480 }
481
482 // Always include IMPLEMENTATION_DEFINED
483 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
484
485 const size_t INTS_PER_CONFIG = 4;
486
487 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700488 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
489
490 Vector<int32_t> streamConfigs;
491 streamConfigs.setCapacity(streamConfigSize);
492
Ruben Brunkb2119af2014-05-09 19:57:56 -0700493 for (size_t i = 0; i < formats.size(); ++i) {
494 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700495 streamConfigs.add(formats[i]);
496 streamConfigs.add(sizes[j].width);
497 streamConfigs.add(sizes[j].height);
498 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700499 }
500 }
501
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700502 for (size_t i = 0; i < jpegSizes.size(); ++i) {
503 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
504 streamConfigs.add(jpegSizes[i].width);
505 streamConfigs.add(jpegSizes[i].height);
506 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
507 }
508
Ruben Brunkb2119af2014-05-09 19:57:56 -0700509 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700510 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700511 return ret;
512 }
513
514 int64_t fakeMinFrames[0];
515 // TODO: Fixme, don't fake min frame durations.
516 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
517 fakeMinFrames, 0)) != OK) {
518 return ret;
519 }
520
521 int64_t fakeStalls[0];
522 // TODO: Fixme, don't fake stall durations.
523 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
524 fakeStalls, 0)) != OK) {
525 return ret;
526 }
527
528 *cameraInfo = shimInfo;
529 return OK;
530}
531
Zhijun He2b59be82013-09-25 10:14:30 -0700532status_t CameraService::getCameraCharacteristics(int cameraId,
533 CameraMetadata* cameraInfo) {
534 if (!cameraInfo) {
535 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
536 return BAD_VALUE;
537 }
538
539 if (!mModule) {
540 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
541 return -ENODEV;
542 }
543
Zhijun He2b59be82013-09-25 10:14:30 -0700544 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
545 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
546 return BAD_VALUE;
547 }
548
549 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700550 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800551 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700552 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
553 /**
554 * Backwards compatibility mode for old HALs:
555 * - Convert CameraInfo into static CameraMetadata properties.
556 * - Retrieve cached CameraParameters for this camera. If none exist,
557 * attempt to open CameraClient and retrieve the CameraParameters.
558 * - Convert cached CameraParameters into static CameraMetadata
559 * properties.
560 */
561 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700562
Ruben Brunkb2119af2014-05-09 19:57:56 -0700563 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
564 return ret;
565 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700566
Ruben Brunkb2119af2014-05-09 19:57:56 -0700567 } else {
568 /**
569 * Normal HAL 2.1+ codepath.
570 */
571 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800572 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700573 *cameraInfo = info.static_camera_characteristics;
574 }
Zhijun He2b59be82013-09-25 10:14:30 -0700575
576 return ret;
577}
578
Ruben Brunkcc776712015-02-17 20:18:47 -0800579int CameraService::getCallingPid() {
580 return IPCThreadState::self()->getCallingPid();
581}
582
583int CameraService::getCallingUid() {
584 return IPCThreadState::self()->getCallingUid();
585}
586
587String8 CameraService::getFormattedCurrentTime() {
588 time_t now = time(nullptr);
589 char formattedTime[64];
590 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
591 return String8(formattedTime);
592}
593
594int CameraService::getCameraPriorityFromProcState(int procState) {
595 // Find the priority for the camera usage based on the process state. Higher priority clients
596 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700597 if (procState < 0) {
598 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
599 procState);
600 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800601 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700602 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800603}
604
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800605status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
606 if (!mModule) {
607 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
608 return -ENODEV;
609 }
610
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800611 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
612 return OK;
613}
614
Igor Murashkin634a5152013-02-20 17:15:11 -0800615int CameraService::getDeviceVersion(int cameraId, int* facing) {
616 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800617 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800618 return -1;
619 }
620
621 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800622 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800623 deviceVersion = info.device_version;
624 } else {
625 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
626 }
627
628 if (facing) {
629 *facing = info.facing;
630 }
631
632 return deviceVersion;
633}
634
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700635status_t CameraService::filterGetInfoErrorCode(status_t err) {
636 switch(err) {
637 case NO_ERROR:
638 case -EINVAL:
639 return err;
640 default:
641 break;
642 }
643 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800644}
645
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800646bool CameraService::setUpVendorTags() {
647 vendor_tag_ops_t vOps = vendor_tag_ops_t();
648
649 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800650 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800651 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
652 return false;
653 }
654
655 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800656 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800657 ATRACE_END();
658
659 // Ensure all vendor operations are present
660 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
661 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
662 vOps.get_tag_type == NULL) {
663 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
664 , __FUNCTION__);
665 return false;
666 }
667
668 // Read all vendor tag definitions into a descriptor
669 sp<VendorTagDescriptor> desc;
670 status_t res;
671 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
672 != OK) {
673 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
674 "received error %s (%d). Camera clients will not be able to use"
675 "vendor tags", __FUNCTION__, strerror(res), res);
676 return false;
677 }
678
679 // Set the global descriptor to use with camera metadata
680 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
681 return true;
682}
683
Ruben Brunkcc776712015-02-17 20:18:47 -0800684status_t CameraService::makeClient(const sp<CameraService>& cameraService,
685 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
686 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
687 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
688 /*out*/sp<BasicClient>* client) {
689
690 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
691 int id = cameraIdToInt(cameraId);
692 if (id == -1) {
693 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
694 cameraId.string());
695 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700696 }
697
Ruben Brunkcc776712015-02-17 20:18:47 -0800698 if (halVersion < 0 || halVersion == deviceVersion) {
699 // Default path: HAL version is unspecified by caller, create CameraClient
700 // based on device version reported by the HAL.
701 switch(deviceVersion) {
702 case CAMERA_DEVICE_API_VERSION_1_0:
703 if (effectiveApiLevel == API_1) { // Camera1 API route
704 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
705 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
706 clientPid, clientUid, getpid(), legacyMode);
707 } else { // Camera2 API route
708 ALOGW("Camera using old HAL version: %d", deviceVersion);
709 return -EOPNOTSUPP;
710 }
711 break;
712 case CAMERA_DEVICE_API_VERSION_2_0:
713 case CAMERA_DEVICE_API_VERSION_2_1:
714 case CAMERA_DEVICE_API_VERSION_3_0:
715 case CAMERA_DEVICE_API_VERSION_3_1:
716 case CAMERA_DEVICE_API_VERSION_3_2:
717 case CAMERA_DEVICE_API_VERSION_3_3:
718 if (effectiveApiLevel == API_1) { // Camera1 API route
719 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
720 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
721 clientPid, clientUid, servicePid, legacyMode);
722 } else { // Camera2 API route
723 sp<ICameraDeviceCallbacks> tmp =
724 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
725 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
726 facing, clientPid, clientUid, servicePid);
727 }
728 break;
729 default:
730 // Should not be reachable
731 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
732 return INVALID_OPERATION;
733 }
734 } else {
735 // A particular HAL version is requested by caller. Create CameraClient
736 // based on the requested HAL version.
737 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
738 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
739 // Only support higher HAL version device opened as HAL1.0 device.
740 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
741 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
742 clientPid, clientUid, servicePid, legacyMode);
743 } else {
744 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
745 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
746 " opened as HAL %x device", halVersion, deviceVersion,
747 CAMERA_DEVICE_API_VERSION_1_0);
748 return INVALID_OPERATION;
749 }
750 }
751 return NO_ERROR;
752}
753
Ruben Brunk6267b532015-04-30 17:44:07 -0700754String8 CameraService::toString(std::set<userid_t> intSet) {
755 String8 s("");
756 bool first = true;
757 for (userid_t i : intSet) {
758 if (first) {
759 s.appendFormat("%d", i);
760 first = false;
761 } else {
762 s.appendFormat(", %d", i);
763 }
764 }
765 return s;
766}
767
Ruben Brunkcc776712015-02-17 20:18:47 -0800768status_t CameraService::initializeShimMetadata(int cameraId) {
769 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700770
771 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800772 String8 id = String8::format("%d", cameraId);
773 status_t ret = NO_ERROR;
774 sp<Client> tmp = nullptr;
775 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
776 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
777 false, true, tmp)) != NO_ERROR) {
778 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
779 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700780 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800781 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700782}
783
Igor Murashkin65d14b92014-06-17 12:03:20 -0700784status_t CameraService::getLegacyParametersLazy(int cameraId,
785 /*out*/
786 CameraParameters* parameters) {
787
788 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
789
790 status_t ret = 0;
791
792 if (parameters == NULL) {
793 ALOGE("%s: parameters must not be null", __FUNCTION__);
794 return BAD_VALUE;
795 }
796
Ruben Brunkcc776712015-02-17 20:18:47 -0800797 String8 id = String8::format("%d", cameraId);
798
799 // Check if we already have parameters
800 {
801 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700802 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800803 auto cameraState = getCameraState(id);
804 if (cameraState == nullptr) {
805 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
806 return BAD_VALUE;
807 }
808 CameraParameters p = cameraState->getShimParams();
809 if (!p.isEmpty()) {
810 *parameters = p;
811 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700812 }
813 }
814
Ruben Brunkcc776712015-02-17 20:18:47 -0800815 int64_t token = IPCThreadState::self()->clearCallingIdentity();
816 ret = initializeShimMetadata(cameraId);
817 IPCThreadState::self()->restoreCallingIdentity(token);
818 if (ret != NO_ERROR) {
819 // Error already logged by callee
820 return ret;
821 }
822
823 // Check for parameters again
824 {
825 // Scope for service lock
826 Mutex::Autolock lock(mServiceLock);
827 auto cameraState = getCameraState(id);
828 if (cameraState == nullptr) {
829 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
830 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700831 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 CameraParameters p = cameraState->getShimParams();
833 if (!p.isEmpty()) {
834 *parameters = p;
835 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700836 }
837 }
838
Ruben Brunkcc776712015-02-17 20:18:47 -0800839 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
840 __FUNCTION__);
841 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700842}
843
Ruben Brunk36597b22015-03-20 22:15:57 -0700844status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
845 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800846
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500848
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800849 if (clientUid == USE_CALLING_UID) {
850 clientUid = getCallingUid();
851 } else {
852 // We only trust our own process to forward client UIDs
853 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700854 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
855 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700856 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800857 }
858 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859
Iliyan Malchev8951a972011-04-14 16:55:59 -0700860 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800861 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
862 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700863 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700864 }
865
Ruben Brunkcc776712015-02-17 20:18:47 -0800866 if (getCameraState(cameraId) == nullptr) {
867 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
868 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700869 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 }
871
Ruben Brunkcc776712015-02-17 20:18:47 -0800872 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800873 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800874 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700875 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800876 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
877 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800878 if (strcmp(value, "1") == 0) {
879 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800880 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
881 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700882 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800883 }
884
Ruben Brunka8ca9152015-04-07 14:23:40 -0700885 // Only allow clients who are being used by the current foreground device user, unless calling
886 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700887 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
888 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
889 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
890 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700891 return PERMISSION_DENIED;
892 }
893
Ruben Brunkcc776712015-02-17 20:18:47 -0800894 return checkIfDeviceIsUsable(cameraId);
895}
896
897status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
898 auto cameraState = getCameraState(cameraId);
899 int callingPid = getCallingPid();
900 if (cameraState == nullptr) {
901 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
902 cameraId.string());
903 return -ENODEV;
904 }
905
906 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700907 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800908 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
909 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700910 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700911 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800912 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
913 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700914 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700915 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700916
Ruben Brunkcc776712015-02-17 20:18:47 -0800917 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800918}
919
Ruben Brunkcc776712015-02-17 20:18:47 -0800920void CameraService::finishConnectLocked(const sp<BasicClient>& client,
921 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800922
Ruben Brunkcc776712015-02-17 20:18:47 -0800923 // Make a descriptor for the incoming client
924 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
925 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
926
927 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
928 String8(client->getPackageName()));
929
930 if (evicted.size() > 0) {
931 // This should never happen - clients should already have been removed in disconnect
932 for (auto& i : evicted) {
933 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
934 __FUNCTION__, i->getKey().string());
935 }
936
937 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
938 __FUNCTION__);
939 }
Eino-Ville Talvala518bcf52015-09-04 14:15:58 -0700940
941 // And register a death notification for the client callback. Do
942 // this last to avoid Binder policy where a nested Binder
943 // transaction might be pre-empted to service the client death
944 // notification if the client process dies before linkToDeath is
945 // invoked.
946 sp<IBinder> remoteCallback = client->getRemote();
947 if (remoteCallback != nullptr) {
948 remoteCallback->linkToDeath(this);
949 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800950}
951
952status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
953 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
954 /*out*/
955 sp<BasicClient>* client,
956 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
957
958 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700959 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800960 DescriptorPtr clientDescriptor;
961 {
962 if (effectiveApiLevel == API_1) {
963 // If we are using API1, any existing client for this camera ID with the same remote
964 // should be returned rather than evicted to allow MediaRecorder to work properly.
965
966 auto current = mActiveClientManager.get(cameraId);
967 if (current != nullptr) {
968 auto clientSp = current->getValue();
969 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700970 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
971 ALOGW("CameraService connect called from same client, but with a different"
972 " API level, evicting prior client...");
973 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800974 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700975 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800976 *client = clientSp;
977 return NO_ERROR;
978 }
979 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800980 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800981 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800982
Ruben Brunkcc776712015-02-17 20:18:47 -0800983 // Return error if the device was unplugged or removed by the HAL for some reason
984 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
985 return ret;
986 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800987
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 // Get current active client PIDs
989 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
990 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800991
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700992 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
993 // address of PROCESS_STATE_NONEXISTENT as a reference argument
994 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
995 // not have an out-of-class definition.
996 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800997
Ruben Brunkcc776712015-02-17 20:18:47 -0800998 // Get priorites of all active PIDs
999 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1000 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -07001001
Ruben Brunkcc776712015-02-17 20:18:47 -08001002 // Update all active clients' priorities
1003 std::map<int,int> pidToPriorityMap;
1004 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1005 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1006 }
1007 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001008
Ruben Brunkcc776712015-02-17 20:18:47 -08001009 // Get state for the given cameraId
1010 auto state = getCameraState(cameraId);
1011 if (state == nullptr) {
1012 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1013 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001014 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001015 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001016
1017 // Make descriptor for incoming client
1018 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1019 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1020 state->getConflicting(),
1021 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1022
1023 // Find clients that would be evicted
1024 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1025
1026 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1027 // background, so we cannot do evictions
1028 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1029 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1030 " priority).", clientPid);
1031
1032 sp<BasicClient> clientSp = clientDescriptor->getValue();
1033 String8 curTime = getFormattedCurrentTime();
1034 auto incompatibleClients =
1035 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1036
1037 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001038 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001039 cameraId.string(), packageName.string(), clientPid,
1040 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1041
1042 for (auto& i : incompatibleClients) {
1043 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1044 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1045 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1046 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001047 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1048 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1049 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1050 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 }
1052
1053 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001054 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001055 mEventLog.add(msg);
1056
1057 return -EBUSY;
1058 }
1059
1060 for (auto& i : evicted) {
1061 sp<BasicClient> clientSp = i->getValue();
1062 if (clientSp.get() == nullptr) {
1063 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1064
1065 // TODO: Remove this
1066 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1067 __FUNCTION__);
1068 mActiveClientManager.remove(i);
1069 continue;
1070 }
1071
1072 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1073 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001074 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001075
Ruben Brunkcc776712015-02-17 20:18:47 -08001076 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001077 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1078 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1079 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001080 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1081 i->getOwnerId(), i->getPriority(), cameraId.string(),
1082 packageName.string(), clientPid,
1083 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1084
1085 // Notify the client of disconnection
1086 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1087 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001088 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001089 }
1090
Ruben Brunkcc776712015-02-17 20:18:47 -08001091 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1092 // other clients from connecting in mServiceLockWrapper if held
1093 mServiceLock.unlock();
1094
1095 // Clear caller identity temporarily so client disconnect PID checks work correctly
1096 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1097
1098 // Destroy evicted clients
1099 for (auto& i : evictedClients) {
1100 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001101 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001102 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001103
1104 IPCThreadState::self()->restoreCallingIdentity(token);
1105
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001106 for (const auto& i : evictedClients) {
1107 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1108 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1109 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1110 if (ret == TIMED_OUT) {
1111 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1112 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1113 mActiveClientManager.toString().string());
1114 return -EBUSY;
1115 }
1116 if (ret != NO_ERROR) {
1117 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1118 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1119 ret, mActiveClientManager.toString().string());
1120 return ret;
1121 }
1122 }
1123
1124 evictedClients.clear();
1125
Ruben Brunkcc776712015-02-17 20:18:47 -08001126 // Once clients have been disconnected, relock
1127 mServiceLock.lock();
1128
1129 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1130 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1131 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001132 }
1133
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 *partial = clientDescriptor;
1135 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001136}
1137
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001138status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001139 const sp<ICameraClient>& cameraClient,
1140 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001141 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001142 int clientUid,
1143 /*out*/
1144 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001145
Ruben Brunkcc776712015-02-17 20:18:47 -08001146 status_t ret = NO_ERROR;
1147 String8 id = String8::format("%d", cameraId);
1148 sp<Client> client = nullptr;
1149 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001150 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001151
Ruben Brunkcc776712015-02-17 20:18:47 -08001152 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001153 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001154 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001155 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 }
1157
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001158 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001159 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160}
1161
Zhijun Heb10cdad2014-06-16 16:38:35 -07001162status_t CameraService::connectLegacy(
1163 const sp<ICameraClient>& cameraClient,
1164 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001165 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001166 int clientUid,
1167 /*out*/
1168 sp<ICamera>& device) {
1169
Ruben Brunka8ca9152015-04-07 14:23:40 -07001170 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001171 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001172 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001173 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001174 /*
1175 * Either the HAL version is unspecified in which case this just creates
1176 * a camera client selected by the latest device version, or
1177 * it's a particular version in which case the HAL must supported
1178 * the open_legacy call
1179 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001180 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001181 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001182 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001183 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001184 return INVALID_OPERATION;
1185 }
1186
Ruben Brunkcc776712015-02-17 20:18:47 -08001187 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001188 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001189 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001191
Ruben Brunkcc776712015-02-17 20:18:47 -08001192 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001193 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001194 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001195 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001196 }
1197
Zhijun Heb10cdad2014-06-16 16:38:35 -07001198 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001199 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001200}
1201
Ruben Brunkcc776712015-02-17 20:18:47 -08001202status_t CameraService::connectDevice(
1203 const sp<ICameraDeviceCallbacks>& cameraCb,
1204 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001205 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001206 int clientUid,
1207 /*out*/
1208 sp<ICameraDeviceUser>& device) {
1209
1210 status_t ret = NO_ERROR;
1211 String8 id = String8::format("%d", cameraId);
1212 sp<CameraDeviceClient> client = nullptr;
1213 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001214 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001215 /*out*/client);
1216
1217 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001218 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001219 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001220 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001221 }
1222
Ruben Brunkcc776712015-02-17 20:18:47 -08001223 device = client;
1224 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001225}
1226
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001227status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1228 const sp<IBinder>& clientBinder) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001229 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001230 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001231 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001232 }
1233
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001234 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001235 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001236
1237 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001238 auto state = getCameraState(id);
1239 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001240 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001241 return -EINVAL;
1242 }
1243
1244 ICameraServiceListener::Status cameraStatus = state->getStatus();
1245 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1246 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001247 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001248 return -EINVAL;
1249 }
1250
1251 {
1252 Mutex::Autolock al(mTorchStatusMutex);
1253 ICameraServiceListener::TorchStatus status;
1254 status_t res = getTorchStatusLocked(id, &status);
1255 if (res) {
1256 ALOGE("%s: getting current torch status failed for camera %s",
1257 __FUNCTION__, id.string());
1258 return -EINVAL;
1259 }
1260
1261 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001262 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001263 ALOGE("%s: torch mode of camera %s is not available because "
1264 "camera is in use", __FUNCTION__, id.string());
1265 return -EBUSY;
1266 } else {
1267 ALOGE("%s: torch mode of camera %s is not available due to "
1268 "insufficient resources", __FUNCTION__, id.string());
1269 return -EUSERS;
1270 }
1271 }
1272 }
1273
Ruben Brunk99e69712015-05-26 17:25:07 -07001274 {
1275 // Update UID map - this is used in the torch status changed callbacks, so must be done
1276 // before setTorchMode
1277 Mutex::Autolock al(mTorchClientMapMutex);
1278 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1279 mTorchUidMap[id].first = uid;
1280 mTorchUidMap[id].second = uid;
1281 } else {
1282 // Set the pending UID
1283 mTorchUidMap[id].first = uid;
1284 }
1285 }
1286
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001287 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001288
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001289 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001290 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1291 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001292 return res;
1293 }
1294
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001295 {
1296 // update the link to client's death
1297 Mutex::Autolock al(mTorchClientMapMutex);
1298 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001299 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001300 if (enabled) {
1301 if (index == NAME_NOT_FOUND) {
1302 mTorchClientMap.add(id, clientBinder);
1303 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001304 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001305 mTorchClientMap.replaceValueAt(index, clientBinder);
1306 }
1307 clientBinder->linkToDeath(this);
1308 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001309 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001310 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001311 }
1312
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001313 return OK;
1314}
1315
Ruben Brunk6267b532015-04-30 17:44:07 -07001316void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001317 switch(eventId) {
1318 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001319 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001320 break;
1321 }
1322 case ICameraService::NO_EVENT:
1323 default: {
1324 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1325 eventId);
1326 break;
1327 }
1328 }
1329}
1330
Ruben Brunk99e69712015-05-26 17:25:07 -07001331status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001332 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001333
Ruben Brunk3450ba72015-06-16 11:00:37 -07001334 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001335 ALOGE("%s: Listener must not be null", __FUNCTION__);
1336 return BAD_VALUE;
1337 }
1338
Igor Murashkinbfc99152013-02-27 12:55:20 -08001339 Mutex::Autolock lock(mServiceLock);
1340
Ruben Brunkcc776712015-02-17 20:18:47 -08001341 {
1342 Mutex::Autolock lock(mStatusListenerLock);
1343 for (auto& it : mListenerList) {
1344 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1345 ALOGW("%s: Tried to add listener %p which was already subscribed",
1346 __FUNCTION__, listener.get());
1347 return ALREADY_EXISTS;
1348 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001349 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001350
1351 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001352 }
1353
Igor Murashkinbfc99152013-02-27 12:55:20 -08001354
Igor Murashkincba2c162013-03-20 15:56:31 -07001355 /* Immediately signal current status to this listener only */
1356 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001357 Mutex::Autolock lock(mCameraStatesLock);
1358 for (auto& i : mCameraStates) {
1359 // TODO: Update binder to use String16 for camera IDs and remove;
1360 int id = cameraIdToInt(i.first);
1361 if (id == -1) continue;
1362
1363 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001364 }
1365 }
1366
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001367 /* Immediately signal current torch status to this listener only */
1368 {
1369 Mutex::Autolock al(mTorchStatusMutex);
1370 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001371 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1372 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001373 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001374 }
1375
Igor Murashkinbfc99152013-02-27 12:55:20 -08001376 return OK;
1377}
Ruben Brunkcc776712015-02-17 20:18:47 -08001378
1379status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001380 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1381
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001382 if (listener == 0) {
1383 ALOGE("%s: Listener must not be null", __FUNCTION__);
1384 return BAD_VALUE;
1385 }
1386
Igor Murashkinbfc99152013-02-27 12:55:20 -08001387 Mutex::Autolock lock(mServiceLock);
1388
Ruben Brunkcc776712015-02-17 20:18:47 -08001389 {
1390 Mutex::Autolock lock(mStatusListenerLock);
1391 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1392 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1393 mListenerList.erase(it);
1394 return OK;
1395 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001396 }
1397 }
1398
1399 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1400 __FUNCTION__, listener.get());
1401
1402 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001403}
1404
Ruben Brunkcc776712015-02-17 20:18:47 -08001405status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001406 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1407
1408 if (parameters == NULL) {
1409 ALOGE("%s: parameters must not be null", __FUNCTION__);
1410 return BAD_VALUE;
1411 }
1412
1413 status_t ret = 0;
1414
1415 CameraParameters shimParams;
1416 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1417 // Error logged by caller
1418 return ret;
1419 }
1420
1421 String8 shimParamsString8 = shimParams.flatten();
1422 String16 shimParamsString16 = String16(shimParamsString8);
1423
1424 *parameters = shimParamsString16;
1425
1426 return OK;
1427}
1428
1429status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1430 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1431
1432 switch (apiVersion) {
1433 case API_VERSION_1:
1434 case API_VERSION_2:
1435 break;
1436 default:
1437 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1438 return BAD_VALUE;
1439 }
1440
1441 int facing = -1;
1442 int deviceVersion = getDeviceVersion(cameraId, &facing);
1443
1444 switch(deviceVersion) {
1445 case CAMERA_DEVICE_API_VERSION_1_0:
1446 case CAMERA_DEVICE_API_VERSION_2_0:
1447 case CAMERA_DEVICE_API_VERSION_2_1:
1448 case CAMERA_DEVICE_API_VERSION_3_0:
1449 case CAMERA_DEVICE_API_VERSION_3_1:
1450 if (apiVersion == API_VERSION_2) {
1451 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1452 __FUNCTION__, cameraId);
1453 return -EOPNOTSUPP;
1454 } else { // if (apiVersion == API_VERSION_1) {
1455 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1456 __FUNCTION__, cameraId);
1457 return OK;
1458 }
1459 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001460 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001461 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1462 __FUNCTION__, cameraId);
1463 return OK;
1464 case -1:
1465 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1466 return BAD_VALUE;
1467 default:
1468 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1469 return INVALID_OPERATION;
1470 }
1471
1472 return OK;
1473}
1474
Ruben Brunkcc776712015-02-17 20:18:47 -08001475void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001476 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001477 for (auto& i : mActiveClientManager.getAll()) {
1478 auto clientSp = i->getValue();
1479 if (clientSp.get() == client) {
1480 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001481 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001482 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001483}
1484
Ruben Brunkcc776712015-02-17 20:18:47 -08001485bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1486 const int callingPid = getCallingPid();
1487 const int servicePid = getpid();
1488 bool ret = false;
1489 {
1490 // Acquire mServiceLock and prevent other clients from connecting
1491 std::unique_ptr<AutoConditionLock> lock =
1492 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001493
Igor Murashkin634a5152013-02-20 17:15:11 -08001494
Ruben Brunkcc776712015-02-17 20:18:47 -08001495 std::vector<sp<BasicClient>> evicted;
1496 for (auto& i : mActiveClientManager.getAll()) {
1497 auto clientSp = i->getValue();
1498 if (clientSp.get() == nullptr) {
1499 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1500 mActiveClientManager.remove(i);
1501 continue;
1502 }
1503 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1504 callingPid == clientSp->getClientPid())) {
1505 mActiveClientManager.remove(i);
1506 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001507
Ruben Brunkcc776712015-02-17 20:18:47 -08001508 // Notify the client of disconnection
1509 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1510 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001511 }
1512 }
1513
Ruben Brunkcc776712015-02-17 20:18:47 -08001514 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1515 // other clients from connecting in mServiceLockWrapper if held
1516 mServiceLock.unlock();
1517
Ruben Brunk36597b22015-03-20 22:15:57 -07001518 // Do not clear caller identity, remote caller should be client proccess
1519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 for (auto& i : evicted) {
1521 if (i.get() != nullptr) {
1522 i->disconnect();
1523 ret = true;
1524 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001525 }
1526
Ruben Brunkcc776712015-02-17 20:18:47 -08001527 // Reacquire mServiceLock
1528 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001529
Ruben Brunkcc776712015-02-17 20:18:47 -08001530 } // lock is destroyed, allow further connect calls
1531
1532 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001533}
1534
Igor Murashkinecf17e82012-10-02 16:05:11 -07001535
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001536/**
1537 * Check camera capabilities, such as support for basic color operation
1538 */
1539int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1540
1541 // Assume all devices pre-v3.3 are backward-compatible
1542 bool isBackwardCompatible = true;
1543 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1544 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1545 isBackwardCompatible = false;
1546 status_t res;
1547 camera_metadata_ro_entry_t caps;
1548 res = find_camera_metadata_ro_entry(
1549 info.static_camera_characteristics,
1550 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1551 &caps);
1552 if (res != 0) {
1553 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1554 __FUNCTION__, id);
1555 caps.count = 0;
1556 }
1557 for (size_t i = 0; i < caps.count; i++) {
1558 if (caps.data.u8[i] ==
1559 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1560 isBackwardCompatible = true;
1561 break;
1562 }
1563 }
1564 }
1565
1566 if (!isBackwardCompatible) {
1567 mNumberOfNormalCameras--;
1568 *latestStrangeCameraId = id;
1569 } else {
1570 if (id > *latestStrangeCameraId) {
1571 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1572 "This is not allowed due backward-compatibility requirements",
1573 __FUNCTION__, id, *latestStrangeCameraId);
1574 logServiceError("Invalid order of camera devices", ENODEV);
1575 mNumberOfCameras = 0;
1576 mNumberOfNormalCameras = 0;
1577 return INVALID_OPERATION;
1578 }
1579 }
1580 return OK;
1581}
1582
Ruben Brunkcc776712015-02-17 20:18:47 -08001583std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1584 const String8& cameraId) const {
1585 std::shared_ptr<CameraState> state;
1586 {
1587 Mutex::Autolock lock(mCameraStatesLock);
1588 auto iter = mCameraStates.find(cameraId);
1589 if (iter != mCameraStates.end()) {
1590 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 }
1592 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001593 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594}
1595
Ruben Brunkcc776712015-02-17 20:18:47 -08001596sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1597 // Remove from active clients list
1598 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1599 if (clientDescriptorPtr == nullptr) {
1600 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1601 cameraId.string());
1602 return sp<BasicClient>{nullptr};
1603 }
1604
1605 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001606}
1607
Ruben Brunk6267b532015-04-30 17:44:07 -07001608void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001609 // Acquire mServiceLock and prevent other clients from connecting
1610 std::unique_ptr<AutoConditionLock> lock =
1611 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1612
Ruben Brunk6267b532015-04-30 17:44:07 -07001613 std::set<userid_t> newAllowedUsers;
1614 for (size_t i = 0; i < length; i++) {
1615 if (newUserId[i] < 0) {
1616 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1617 __FUNCTION__, newUserId[i]);
1618 return;
1619 }
1620 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001621 }
1622
Ruben Brunka8ca9152015-04-07 14:23:40 -07001623
Ruben Brunk6267b532015-04-30 17:44:07 -07001624 if (newAllowedUsers == mAllowedUsers) {
1625 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1626 return;
1627 }
1628
1629 logUserSwitch(mAllowedUsers, newAllowedUsers);
1630
1631 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001632
1633 // Current user has switched, evict all current clients.
1634 std::vector<sp<BasicClient>> evicted;
1635 for (auto& i : mActiveClientManager.getAll()) {
1636 auto clientSp = i->getValue();
1637
1638 if (clientSp.get() == nullptr) {
1639 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1640 continue;
1641 }
1642
Ruben Brunk6267b532015-04-30 17:44:07 -07001643 // Don't evict clients that are still allowed.
1644 uid_t clientUid = clientSp->getClientUid();
1645 userid_t clientUserId = multiuser_get_user_id(clientUid);
1646 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1647 continue;
1648 }
1649
Ruben Brunk36597b22015-03-20 22:15:57 -07001650 evicted.push_back(clientSp);
1651
1652 String8 curTime = getFormattedCurrentTime();
1653
1654 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1655 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001656
Ruben Brunk36597b22015-03-20 22:15:57 -07001657 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001658 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001659 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001660 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1661 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001662
1663 }
1664
1665 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1666 // blocking other clients from connecting in mServiceLockWrapper if held.
1667 mServiceLock.unlock();
1668
1669 // Clear caller identity temporarily so client disconnect PID checks work correctly
1670 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1671
1672 for (auto& i : evicted) {
1673 i->disconnect();
1674 }
1675
1676 IPCThreadState::self()->restoreCallingIdentity(token);
1677
1678 // Reacquire mServiceLock
1679 mServiceLock.lock();
1680}
Ruben Brunkcc776712015-02-17 20:18:47 -08001681
Ruben Brunka8ca9152015-04-07 14:23:40 -07001682void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001683 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001684 Mutex::Autolock l(mLogLock);
1685 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686}
1687
Ruben Brunka8ca9152015-04-07 14:23:40 -07001688void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001689 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001690 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001691 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001692 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001693}
1694
1695void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001696 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001697 // Log the clients evicted
1698 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001699 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001700}
1701
1702void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001703 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001704 // Log the client rejected
1705 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001706 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001707}
1708
Ruben Brunk6267b532015-04-30 17:44:07 -07001709void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1710 const std::set<userid_t>& newUserIds) {
1711 String8 newUsers = toString(newUserIds);
1712 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001713 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001714 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1715 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001716}
1717
1718void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1719 // Log the device removal
1720 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1721}
1722
1723void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1724 // Log the device removal
1725 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1726}
1727
1728void CameraService::logClientDied(int clientPid, const char* reason) {
1729 // Log the device removal
1730 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001731}
1732
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001733void CameraService::logServiceError(const char* msg, int errorCode) {
1734 String8 curTime = getFormattedCurrentTime();
1735 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1736}
1737
Ruben Brunk36597b22015-03-20 22:15:57 -07001738status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1739 uint32_t flags) {
1740
1741 const int pid = getCallingPid();
1742 const int selfPid = getpid();
1743
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 // Permission checks
1745 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001746 case BnCameraService::CONNECT:
1747 case BnCameraService::CONNECT_DEVICE:
1748 case BnCameraService::CONNECT_LEGACY: {
1749 if (pid != selfPid) {
1750 // we're called from a different process, do the real check
1751 if (!checkCallingPermission(
1752 String16("android.permission.CAMERA"))) {
1753 const int uid = getCallingUid();
1754 ALOGE("Permission Denial: "
1755 "can't use the camera pid=%d, uid=%d", pid, uid);
1756 return PERMISSION_DENIED;
1757 }
1758 }
1759 break;
1760 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001761 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1762 if (pid != selfPid) {
1763 // Ensure we're being called by system_server, or similar process with
1764 // permissions to notify the camera service about system events
1765 if (!checkCallingPermission(
1766 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1767 const int uid = getCallingUid();
1768 ALOGE("Permission Denial: cannot send updates to camera service about system"
1769 " events from pid=%d, uid=%d", pid, uid);
1770 return PERMISSION_DENIED;
1771 }
1772 }
1773 break;
1774 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775 }
1776
1777 return BnCameraService::onTransact(code, data, reply, flags);
1778}
1779
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780// We share the media players for shutter and recording sound for all clients.
1781// A reference count is kept to determine when we will actually release the
1782// media players.
1783
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001784MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001786 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001787 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 mp->prepare();
1789 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001790 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 return NULL;
1792 }
1793 return mp;
1794}
1795
1796void CameraService::loadSound() {
1797 Mutex::Autolock lock(mSoundLock);
1798 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1799 if (mSoundRef++) return;
1800
1801 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1802 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1803}
1804
1805void CameraService::releaseSound() {
1806 Mutex::Autolock lock(mSoundLock);
1807 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1808 if (--mSoundRef) return;
1809
1810 for (int i = 0; i < NUM_SOUNDS; i++) {
1811 if (mSoundPlayer[i] != 0) {
1812 mSoundPlayer[i]->disconnect();
1813 mSoundPlayer[i].clear();
1814 }
1815 }
1816}
1817
1818void CameraService::playSound(sound_kind kind) {
1819 LOG1("playSound(%d)", kind);
1820 Mutex::Autolock lock(mSoundLock);
1821 sp<MediaPlayer> player = mSoundPlayer[kind];
1822 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001823 player->seekTo(0);
1824 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 }
1826}
1827
1828// ----------------------------------------------------------------------------
1829
1830CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001831 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001832 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001833 int cameraId, int cameraFacing,
1834 int clientPid, uid_t clientUid,
1835 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001836 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001837 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001838 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001839 cameraId, cameraFacing,
1840 clientPid, clientUid,
1841 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001842{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001844 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001846 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001849
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001850 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851}
1852
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853// tear down the client
1854CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001855 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001856 mDestructionStarted = true;
1857
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001858 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001859 // unconditionally disconnect. function is idempotent
1860 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
Igor Murashkin634a5152013-02-20 17:15:11 -08001863CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001864 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001865 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001866 int cameraId, int cameraFacing,
1867 int clientPid, uid_t clientUid,
1868 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001869 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001870{
1871 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001872 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001873 mCameraId = cameraId;
1874 mCameraFacing = cameraFacing;
1875 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001876 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001877 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001878 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001879 mDestructionStarted = false;
1880}
1881
1882CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001883 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001884 mDestructionStarted = true;
1885}
1886
1887void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001888 if (mDisconnected) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001889 return;
1890 }
Eino-Ville Talvala518bcf52015-09-04 14:15:58 -07001891 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08001892
1893 mCameraService->removeByClient(this);
1894 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001895 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001896
1897 sp<IBinder> remote = getRemote();
1898 if (remote != nullptr) {
1899 remote->unlinkToDeath(mCameraService);
1900 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001901
1902 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001903 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1904
Igor Murashkincba2c162013-03-20 15:56:31 -07001905 // client shouldn't be able to call into us anymore
1906 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001907}
1908
Ruben Brunkcc776712015-02-17 20:18:47 -08001909String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001910 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001911}
1912
1913
1914int CameraService::BasicClient::getClientPid() const {
1915 return mClientPid;
1916}
1917
Ruben Brunk6267b532015-04-30 17:44:07 -07001918uid_t CameraService::BasicClient::getClientUid() const {
1919 return mClientUid;
1920}
1921
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001922bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1923 // Defaults to API2.
1924 return level == API_2;
1925}
1926
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001927status_t CameraService::BasicClient::startCameraOps() {
1928 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001929 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001930 mOpsCallback = new OpsCallback(this);
1931
Igor Murashkine6800ce2013-03-04 17:25:57 -08001932 {
1933 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001934 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001935 }
1936
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001937 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001938 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001939 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001940 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001941
Svetoslav28e8ef72015-05-11 19:21:31 -07001942 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001943 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001944 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001945 return PERMISSION_DENIED;
1946 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001947
Svetoslav28e8ef72015-05-11 19:21:31 -07001948 if (res == AppOpsManager::MODE_IGNORED) {
1949 ALOGI("Camera %d: Access for \"%s\" has been restricted",
1950 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07001951 // Return the same error as for device policy manager rejection
1952 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07001953 }
1954
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001955 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001956
1957 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1958 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001959 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001960
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001961 return OK;
1962}
1963
1964status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001965 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001966 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001967 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001968 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001969 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001970 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001971
Ruben Brunkcc776712015-02-17 20:18:47 -08001972 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1973 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001974
Ruben Brunkcc776712015-02-17 20:18:47 -08001975 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001976 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001977 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001978
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001979 // Notify flashlight that a camera device is closed.
1980 mCameraService->mFlashlight->deviceClosed(
1981 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001982 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001983 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001984 if (mOpsCallback != NULL) {
1985 mAppOpsManager.stopWatchingMode(mOpsCallback);
1986 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001987 mOpsCallback.clear();
1988
1989 return OK;
1990}
1991
1992void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1993 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001994 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001995
1996 if (op != AppOpsManager::OP_CAMERA) {
1997 ALOGW("Unexpected app ops notification received: %d", op);
1998 return;
1999 }
2000
2001 int32_t res;
2002 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002003 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002004 ALOGV("checkOp returns: %d, %s ", res,
2005 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2006 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2007 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2008 "UNKNOWN");
2009
2010 if (res != AppOpsManager::MODE_ALLOWED) {
2011 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2012 myName.string());
2013 // Reset the client PID to allow server-initiated disconnect,
2014 // and to prevent further calls by client.
2015 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002016 CaptureResultExtras resultExtras; // a dummy result (invalid)
2017 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002018 disconnect();
2019 }
2020}
2021
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022// ----------------------------------------------------------------------------
2023
Ruben Brunkcc776712015-02-17 20:18:47 -08002024// Provide client strong pointer for callbacks.
2025sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2026 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2027 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2028 if (clientDescriptor != nullptr) {
2029 return sp<Client>{
2030 static_cast<Client*>(clientDescriptor->getValue().get())};
2031 }
2032 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033}
2034
Jianing Weicb0652e2014-03-12 18:29:36 -07002035void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2036 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002037 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002038}
2039
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002040// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002041void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002042 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002043 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002044}
2045
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002046bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2047 return level == API_1;
2048}
2049
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002050CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2051 mClient(client) {
2052}
2053
2054void CameraService::Client::OpsCallback::opChanged(int32_t op,
2055 const String16& packageName) {
2056 sp<BasicClient> client = mClient.promote();
2057 if (client != NULL) {
2058 client->opChanged(op, packageName);
2059 }
2060}
2061
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002063// CameraState
2064// ----------------------------------------------------------------------------
2065
2066CameraService::CameraState::CameraState(const String8& id, int cost,
2067 const std::set<String8>& conflicting) : mId(id),
2068 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2069
2070CameraService::CameraState::~CameraState() {}
2071
2072ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2073 Mutex::Autolock lock(mStatusLock);
2074 return mStatus;
2075}
2076
2077CameraParameters CameraService::CameraState::getShimParams() const {
2078 return mShimParams;
2079}
2080
2081void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2082 mShimParams = params;
2083}
2084
2085int CameraService::CameraState::getCost() const {
2086 return mCost;
2087}
2088
2089std::set<String8> CameraService::CameraState::getConflicting() const {
2090 return mConflicting;
2091}
2092
2093String8 CameraService::CameraState::getId() const {
2094 return mId;
2095}
2096
2097// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002098// ClientEventListener
2099// ----------------------------------------------------------------------------
2100
2101void CameraService::ClientEventListener::onClientAdded(
2102 const resource_policy::ClientDescriptor<String8,
2103 sp<CameraService::BasicClient>>& descriptor) {
2104 auto basicClient = descriptor.getValue();
2105 if (basicClient.get() != nullptr) {
2106 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2107 notifier.noteStartCamera(descriptor.getKey(),
2108 static_cast<int>(basicClient->getClientUid()));
2109 }
2110}
2111
2112void CameraService::ClientEventListener::onClientRemoved(
2113 const resource_policy::ClientDescriptor<String8,
2114 sp<CameraService::BasicClient>>& descriptor) {
2115 auto basicClient = descriptor.getValue();
2116 if (basicClient.get() != nullptr) {
2117 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2118 notifier.noteStopCamera(descriptor.getKey(),
2119 static_cast<int>(basicClient->getClientUid()));
2120 }
2121}
2122
2123
2124// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002125// CameraClientManager
2126// ----------------------------------------------------------------------------
2127
Ruben Brunk99e69712015-05-26 17:25:07 -07002128CameraService::CameraClientManager::CameraClientManager() {
2129 setListener(std::make_shared<ClientEventListener>());
2130}
2131
Ruben Brunkcc776712015-02-17 20:18:47 -08002132CameraService::CameraClientManager::~CameraClientManager() {}
2133
2134sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2135 const String8& id) const {
2136 auto descriptor = get(id);
2137 if (descriptor == nullptr) {
2138 return sp<BasicClient>{nullptr};
2139 }
2140 return descriptor->getValue();
2141}
2142
2143String8 CameraService::CameraClientManager::toString() const {
2144 auto all = getAll();
2145 String8 ret("[");
2146 bool hasAny = false;
2147 for (auto& i : all) {
2148 hasAny = true;
2149 String8 key = i->getKey();
2150 int32_t cost = i->getCost();
2151 int32_t pid = i->getOwnerId();
2152 int32_t priority = i->getPriority();
2153 auto conflicting = i->getConflicting();
2154 auto clientSp = i->getValue();
2155 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002156 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002157 if (clientSp.get() != nullptr) {
2158 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002159 uid_t clientUid = clientSp->getClientUid();
2160 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002161 }
2162 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2163 PRId32 ", ", key.string(), cost, pid, priority);
2164
Ruben Brunk6267b532015-04-30 17:44:07 -07002165 if (clientSp.get() != nullptr) {
2166 ret.appendFormat("User Id: %d, ", clientUserId);
2167 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002168 if (packageName.size() != 0) {
2169 ret.appendFormat("Client Package Name: %s", packageName.string());
2170 }
2171
2172 ret.append(", Conflicting Client Devices: {");
2173 for (auto& j : conflicting) {
2174 ret.appendFormat("%s, ", j.string());
2175 }
2176 ret.append("})");
2177 }
2178 if (hasAny) ret.append("\n");
2179 ret.append("]\n");
2180 return ret;
2181}
2182
2183CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2184 const String8& key, const sp<BasicClient>& value, int32_t cost,
2185 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2186
2187 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2188 key, value, cost, conflictingKeys, priority, ownerId);
2189}
2190
2191CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2192 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2193 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2194 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2195}
2196
2197// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198
2199static const int kDumpLockRetries = 50;
2200static const int kDumpLockSleep = 60000;
2201
2202static bool tryLock(Mutex& mutex)
2203{
2204 bool locked = false;
2205 for (int i = 0; i < kDumpLockRetries; ++i) {
2206 if (mutex.tryLock() == NO_ERROR) {
2207 locked = true;
2208 break;
2209 }
2210 usleep(kDumpLockSleep);
2211 }
2212 return locked;
2213}
2214
2215status_t CameraService::dump(int fd, const Vector<String16>& args) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002216 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002218 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 "can't dump CameraService from pid=%d, uid=%d\n",
2220 getCallingPid(),
2221 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 write(fd, result.string(), result.size());
2223 } else {
2224 bool locked = tryLock(mServiceLock);
2225 // failed to lock - CameraService is probably deadlocked
2226 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002227 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002228 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 }
2230
2231 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002232 if (!mModule) {
2233 result = String8::format("No camera module available!\n");
2234 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002235
2236 // Dump event log for error information
2237 dumpEventLog(fd);
2238
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002239 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002240 return NO_ERROR;
2241 }
2242
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002243 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2244 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2245 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2246 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002247 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2248 String8 activeClientString = mActiveClientManager.toString();
2249 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002250 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002251
Ruben Brunkf81648e2014-04-17 16:14:57 -07002252 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2253 if (desc == NULL) {
2254 result.appendFormat("Vendor tags left unimplemented.\n");
2255 } else {
2256 result.appendFormat("Vendor tag definitions:\n");
2257 }
2258
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002259 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002260
2261 if (desc != NULL) {
2262 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2263 }
2264
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002265 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002266
2267 bool stateLocked = tryLock(mCameraStatesLock);
2268 if (!stateLocked) {
2269 result = String8::format("CameraStates in use, may be deadlocked\n");
2270 write(fd, result.string(), result.size());
2271 }
2272
2273 for (auto& state : mCameraStates) {
2274 String8 cameraId = state.first;
2275 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002276 camera_info info;
2277
Ruben Brunkcc776712015-02-17 20:18:47 -08002278 // TODO: Change getCameraInfo + HAL to use String cameraIds
2279 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002280 if (rc != OK) {
2281 result.appendFormat(" Error reading static information!\n");
2282 write(fd, result.string(), result.size());
2283 } else {
2284 result.appendFormat(" Facing: %s\n",
2285 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2286 result.appendFormat(" Orientation: %d\n", info.orientation);
2287 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002288 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002289 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2290 } else {
2291 deviceVersion = info.device_version;
2292 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002293
2294 auto conflicting = state.second->getConflicting();
2295 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2296 result.appendFormat(" Conflicting Devices:");
2297 for (auto& id : conflicting) {
2298 result.appendFormat(" %s", cameraId.string());
2299 }
2300 if (conflicting.size() == 0) {
2301 result.appendFormat(" NONE");
2302 }
2303 result.appendFormat("\n");
2304
2305 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002306 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2307 result.appendFormat(" Device static metadata:\n");
2308 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002309 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002310 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002311 } else {
2312 write(fd, result.string(), result.size());
2313 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002314
2315 CameraParameters p = state.second->getShimParams();
2316 if (!p.isEmpty()) {
2317 result = String8::format(" Camera1 API shim is using parameters:\n ");
2318 write(fd, result.string(), result.size());
2319 p.dump(fd, args);
2320 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002321 }
2322
Ruben Brunkcc776712015-02-17 20:18:47 -08002323 auto clientDescriptor = mActiveClientManager.get(cameraId);
2324 if (clientDescriptor == nullptr) {
2325 result = String8::format(" Device %s is closed, no client instance\n",
2326 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002327 write(fd, result.string(), result.size());
2328 continue;
2329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002331 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2332 cameraId.string());
2333 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2334 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2335
2336 auto client = clientDescriptor->getValue();
2337 result.appendFormat("Client package: %s\n",
2338 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002339 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002340
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002341 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002343
2344 if (stateLocked) mCameraStatesLock.unlock();
2345
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002347 result = String8::format("\nNo active camera clients yet.\n");
2348 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 }
2350
2351 if (locked) mServiceLock.unlock();
2352
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002353 // Dump camera traces if there were any
2354 write(fd, "\n", 1);
2355 camera3::CameraTraces::dump(fd, args);
2356
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 // change logging level
2358 int n = args.size();
2359 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002360 String16 verboseOption("-v");
2361 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002362 String8 levelStr(args[i+1]);
2363 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002364 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002366 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 }
2368 }
2369 }
2370 return NO_ERROR;
2371}
2372
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002373void CameraService::dumpEventLog(int fd) {
2374 String8 result = String8("\nPrior client events (most recent at top):\n");
2375
2376 Mutex::Autolock l(mLogLock);
2377 for (const auto& msg : mEventLog) {
2378 result.appendFormat(" %s\n", msg.string());
2379 }
2380
2381 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2382 result.append(" ...\n");
2383 } else if (mEventLog.size() == 0) {
2384 result.append(" [no events yet]\n");
2385 }
2386 result.append("\n");
2387
2388 write(fd, result.string(), result.size());
2389}
2390
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002391void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002392 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002393 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2394 if (mTorchClientMap[i] == who) {
2395 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002396 String8 cameraId = mTorchClientMap.keyAt(i);
2397 status_t res = mFlashlight->setTorchMode(cameraId, false);
2398 if (res) {
2399 ALOGE("%s: torch client died but couldn't turn off torch: "
2400 "%s (%d)", __FUNCTION__, strerror(-res), res);
2401 return;
2402 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002403 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002404 break;
2405 }
2406 }
2407}
2408
Ruben Brunkcc776712015-02-17 20:18:47 -08002409/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002410
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002411 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002412 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2413 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002414 */
2415
Ruben Brunka8ca9152015-04-07 14:23:40 -07002416 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2417
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002418 // check torch client
2419 handleTorchClientBinderDied(who);
2420
2421 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002422 if(!evictClientIdByRemote(who)) {
2423 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002424 return;
2425 }
2426
Ruben Brunkcc776712015-02-17 20:18:47 -08002427 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2428 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002429}
2430
Ruben Brunkcc776712015-02-17 20:18:47 -08002431void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2432 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002433}
2434
Ruben Brunkcc776712015-02-17 20:18:47 -08002435void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2436 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2437 // Do not lock mServiceLock here or can get into a deadlock from
2438 // connect() -> disconnect -> updateStatus
2439
2440 auto state = getCameraState(cameraId);
2441
2442 if (state == nullptr) {
2443 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2444 cameraId.string());
2445 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002446 }
2447
Ruben Brunkcc776712015-02-17 20:18:47 -08002448 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2449 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2450 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2451 (const String8& cameraId, ICameraServiceListener::Status status) {
2452
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002453 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2454 // Update torch status if it has a flash unit.
2455 Mutex::Autolock al(mTorchStatusMutex);
2456 ICameraServiceListener::TorchStatus torchStatus;
2457 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2458 NAME_NOT_FOUND) {
2459 ICameraServiceListener::TorchStatus newTorchStatus =
2460 status == ICameraServiceListener::STATUS_PRESENT ?
2461 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2462 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2463 if (torchStatus != newTorchStatus) {
2464 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2465 }
2466 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002467 }
2468
2469 Mutex::Autolock lock(mStatusListenerLock);
2470
2471 for (auto& listener : mListenerList) {
2472 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2473 int id = cameraIdToInt(cameraId);
2474 if (id != -1) listener->onStatusChanged(status, id);
2475 }
2476 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002477}
2478
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002479status_t CameraService::getTorchStatusLocked(
2480 const String8& cameraId,
2481 ICameraServiceListener::TorchStatus *status) const {
2482 if (!status) {
2483 return BAD_VALUE;
2484 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002485 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2486 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002487 // invalid camera ID or the camera doesn't have a flash unit
2488 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002489 }
2490
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002491 *status = mTorchStatusMap.valueAt(index);
2492 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002493}
2494
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002495status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002496 ICameraServiceListener::TorchStatus status) {
2497 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2498 if (index == NAME_NOT_FOUND) {
2499 return BAD_VALUE;
2500 }
2501 ICameraServiceListener::TorchStatus& item =
2502 mTorchStatusMap.editValueAt(index);
2503 item = status;
2504
2505 return OK;
2506}
2507
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508}; // namespace android