blob: 43a8ec4e3f365242622f43971c0a68df284f4d09 [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
311 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
312 CaptureResultExtras{});
Igor Murashkincba2c162013-03-20 15:56:31 -0700313 }
314
Ruben Brunkcc776712015-02-17 20:18:47 -0800315 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
316 __FUNCTION__, id.string());
Igor Murashkincba2c162013-03-20 15:56:31 -0700317
Ruben Brunkcc776712015-02-17 20:18:47 -0800318 // Disconnect client
319 if (clientToDisconnect.get() != nullptr) {
320 // Ensure not in binder RPC so client disconnect PID checks work correctly
321 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
322 "onDeviceStatusChanged must be called from the camera service process!");
323 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700324 }
325
Ruben Brunkcc776712015-02-17 20:18:47 -0800326 } else {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700327 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
328 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
329 newStatus));
330 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800331 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700332 }
333
Igor Murashkincba2c162013-03-20 15:56:31 -0700334}
335
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800336void CameraService::onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800337 ICameraServiceListener::TorchStatus newStatus) {
338 Mutex::Autolock al(mTorchStatusMutex);
339 onTorchStatusChangedLocked(cameraId, newStatus);
340}
341
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800342void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800343 ICameraServiceListener::TorchStatus newStatus) {
344 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
345 __FUNCTION__, cameraId.string(), newStatus);
346
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800347 ICameraServiceListener::TorchStatus status;
348 status_t res = getTorchStatusLocked(cameraId, &status);
349 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700350 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
351 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800352 return;
353 }
354 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800355 return;
356 }
357
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800358 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800359 if (res) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700360 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800361 return;
362 }
363
Ruben Brunkcc776712015-02-17 20:18:47 -0800364 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700365 // Update battery life logging for flashlight
366 Mutex::Autolock al(mTorchClientMapMutex);
367 auto iter = mTorchUidMap.find(cameraId);
368 if (iter != mTorchUidMap.end()) {
369 int oldUid = iter->second.second;
370 int newUid = iter->second.first;
371 BatteryNotifier& notifier(BatteryNotifier::getInstance());
372 if (oldUid != newUid) {
373 // If the UID has changed, log the status and update current UID in mTorchUidMap
374 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
375 notifier.noteFlashlightOff(cameraId, oldUid);
376 }
377 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
378 notifier.noteFlashlightOn(cameraId, newUid);
379 }
380 iter->second.second = newUid;
381 } else {
382 // If the UID has not changed, log the status
383 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
384 notifier.noteFlashlightOn(cameraId, oldUid);
385 } else {
386 notifier.noteFlashlightOff(cameraId, oldUid);
387 }
388 }
389 }
390 }
391
392 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800393 Mutex::Autolock lock(mStatusListenerLock);
394 for (auto& i : mListenerList) {
395 i->onTorchStatusChanged(newStatus, String16{cameraId});
396 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800397 }
398}
399
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400int32_t CameraService::getNumberOfCameras() {
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700401 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
402}
403
404int32_t CameraService::getNumberOfCameras(int type) {
405 switch (type) {
406 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
407 return mNumberOfNormalCameras;
408 case CAMERA_TYPE_ALL:
409 return mNumberOfCameras;
410 default:
411 ALOGW("%s: Unknown camera type %d, returning 0",
412 __FUNCTION__, type);
413 return 0;
414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415}
416
417status_t CameraService::getCameraInfo(int cameraId,
418 struct CameraInfo* cameraInfo) {
Iliyan Malchev8951a972011-04-14 16:55:59 -0700419 if (!mModule) {
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700420 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700421 }
422
Mathias Agopian65ab4712010-07-14 17:59:35 -0700423 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
424 return BAD_VALUE;
425 }
426
Iliyan Malchev8951a972011-04-14 16:55:59 -0700427 struct camera_info info;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700428 status_t rc = filterGetInfoErrorCode(
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800429 mModule->getCameraInfo(cameraId, &info));
Iliyan Malchev8951a972011-04-14 16:55:59 -0700430 cameraInfo->facing = info.facing;
431 cameraInfo->orientation = info.orientation;
432 return rc;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433}
434
Ruben Brunkcc776712015-02-17 20:18:47 -0800435int CameraService::cameraIdToInt(const String8& cameraId) {
436 errno = 0;
437 size_t pos = 0;
438 int ret = stoi(std::string{cameraId.string()}, &pos);
439 if (errno != 0 || pos != cameraId.size()) {
440 return -1;
441 }
442 return ret;
443}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700444
445status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
446 status_t ret = OK;
447 struct CameraInfo info;
448 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
449 return ret;
450 }
451
452 CameraMetadata shimInfo;
453 int32_t orientation = static_cast<int32_t>(info.orientation);
454 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
455 return ret;
456 }
457
458 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
459 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
460 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
461 return ret;
462 }
463
Igor Murashkin65d14b92014-06-17 12:03:20 -0700464 CameraParameters shimParams;
465 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
466 // Error logged by callee
467 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700468 }
469
470 Vector<Size> sizes;
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700471 Vector<Size> jpegSizes;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700472 Vector<int32_t> formats;
473 const char* supportedPreviewFormats;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700474 {
475 shimParams.getSupportedPreviewSizes(/*out*/sizes);
476 shimParams.getSupportedPreviewFormats(/*out*/formats);
477 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700478 }
479
480 // Always include IMPLEMENTATION_DEFINED
481 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
482
483 const size_t INTS_PER_CONFIG = 4;
484
485 // Build available stream configurations metadata
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700486 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
487
488 Vector<int32_t> streamConfigs;
489 streamConfigs.setCapacity(streamConfigSize);
490
Ruben Brunkb2119af2014-05-09 19:57:56 -0700491 for (size_t i = 0; i < formats.size(); ++i) {
492 for (size_t j = 0; j < sizes.size(); ++j) {
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700493 streamConfigs.add(formats[i]);
494 streamConfigs.add(sizes[j].width);
495 streamConfigs.add(sizes[j].height);
496 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700497 }
498 }
499
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700500 for (size_t i = 0; i < jpegSizes.size(); ++i) {
501 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
502 streamConfigs.add(jpegSizes[i].width);
503 streamConfigs.add(jpegSizes[i].height);
504 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
505 }
506
Ruben Brunkb2119af2014-05-09 19:57:56 -0700507 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
Ruben Brunk152dbcf2014-06-12 19:11:45 -0700508 streamConfigs.array(), streamConfigSize)) != OK) {
Ruben Brunkb2119af2014-05-09 19:57:56 -0700509 return ret;
510 }
511
512 int64_t fakeMinFrames[0];
513 // TODO: Fixme, don't fake min frame durations.
514 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
515 fakeMinFrames, 0)) != OK) {
516 return ret;
517 }
518
519 int64_t fakeStalls[0];
520 // TODO: Fixme, don't fake stall durations.
521 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
522 fakeStalls, 0)) != OK) {
523 return ret;
524 }
525
526 *cameraInfo = shimInfo;
527 return OK;
528}
529
Zhijun He2b59be82013-09-25 10:14:30 -0700530status_t CameraService::getCameraCharacteristics(int cameraId,
531 CameraMetadata* cameraInfo) {
532 if (!cameraInfo) {
533 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
534 return BAD_VALUE;
535 }
536
537 if (!mModule) {
538 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
539 return -ENODEV;
540 }
541
Zhijun He2b59be82013-09-25 10:14:30 -0700542 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
543 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
544 return BAD_VALUE;
545 }
546
547 int facing;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700548 status_t ret = OK;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800549 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
Ruben Brunkb2119af2014-05-09 19:57:56 -0700550 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
551 /**
552 * Backwards compatibility mode for old HALs:
553 * - Convert CameraInfo into static CameraMetadata properties.
554 * - Retrieve cached CameraParameters for this camera. If none exist,
555 * attempt to open CameraClient and retrieve the CameraParameters.
556 * - Convert cached CameraParameters into static CameraMetadata
557 * properties.
558 */
559 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
Zhijun He2b59be82013-09-25 10:14:30 -0700560
Ruben Brunkb2119af2014-05-09 19:57:56 -0700561 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
562 return ret;
563 }
Zhijun Hef05e50e2013-10-01 11:05:33 -0700564
Ruben Brunkb2119af2014-05-09 19:57:56 -0700565 } else {
566 /**
567 * Normal HAL 2.1+ codepath.
568 */
569 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800570 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
Ruben Brunkb2119af2014-05-09 19:57:56 -0700571 *cameraInfo = info.static_camera_characteristics;
572 }
Zhijun He2b59be82013-09-25 10:14:30 -0700573
574 return ret;
575}
576
Ruben Brunkcc776712015-02-17 20:18:47 -0800577int CameraService::getCallingPid() {
578 return IPCThreadState::self()->getCallingPid();
579}
580
581int CameraService::getCallingUid() {
582 return IPCThreadState::self()->getCallingUid();
583}
584
585String8 CameraService::getFormattedCurrentTime() {
586 time_t now = time(nullptr);
587 char formattedTime[64];
588 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
589 return String8(formattedTime);
590}
591
592int CameraService::getCameraPriorityFromProcState(int procState) {
593 // Find the priority for the camera usage based on the process state. Higher priority clients
594 // win for evictions.
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700595 if (procState < 0) {
596 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
597 procState);
598 return -1;
Ruben Brunkcc776712015-02-17 20:18:47 -0800599 }
Ruben Brunkbe0b6b42015-05-12 16:10:52 -0700600 return INT_MAX - procState;
Ruben Brunkcc776712015-02-17 20:18:47 -0800601}
602
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800603status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
604 if (!mModule) {
605 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
606 return -ENODEV;
607 }
608
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800609 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
610 return OK;
611}
612
Igor Murashkin634a5152013-02-20 17:15:11 -0800613int CameraService::getDeviceVersion(int cameraId, int* facing) {
614 struct camera_info info;
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800615 if (mModule->getCameraInfo(cameraId, &info) != OK) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800616 return -1;
617 }
618
619 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -0800620 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
Igor Murashkin634a5152013-02-20 17:15:11 -0800621 deviceVersion = info.device_version;
622 } else {
623 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
624 }
625
626 if (facing) {
627 *facing = info.facing;
628 }
629
630 return deviceVersion;
631}
632
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700633status_t CameraService::filterGetInfoErrorCode(status_t err) {
634 switch(err) {
635 case NO_ERROR:
636 case -EINVAL:
637 return err;
638 default:
639 break;
640 }
641 return -ENODEV;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800642}
643
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800644bool CameraService::setUpVendorTags() {
645 vendor_tag_ops_t vOps = vendor_tag_ops_t();
646
647 // Check if vendor operations have been implemented
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800648 if (!mModule->isVendorTagDefined()) {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800649 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
650 return false;
651 }
652
653 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800654 mModule->getVendorTagOps(&vOps);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800655 ATRACE_END();
656
657 // Ensure all vendor operations are present
658 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
659 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
660 vOps.get_tag_type == NULL) {
661 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
662 , __FUNCTION__);
663 return false;
664 }
665
666 // Read all vendor tag definitions into a descriptor
667 sp<VendorTagDescriptor> desc;
668 status_t res;
669 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
670 != OK) {
671 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
672 "received error %s (%d). Camera clients will not be able to use"
673 "vendor tags", __FUNCTION__, strerror(res), res);
674 return false;
675 }
676
677 // Set the global descriptor to use with camera metadata
678 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
679 return true;
680}
681
Ruben Brunkcc776712015-02-17 20:18:47 -0800682status_t CameraService::makeClient(const sp<CameraService>& cameraService,
683 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
684 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
685 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
686 /*out*/sp<BasicClient>* client) {
687
688 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
689 int id = cameraIdToInt(cameraId);
690 if (id == -1) {
691 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
692 cameraId.string());
693 return BAD_VALUE;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700694 }
695
Ruben Brunkcc776712015-02-17 20:18:47 -0800696 if (halVersion < 0 || halVersion == deviceVersion) {
697 // Default path: HAL version is unspecified by caller, create CameraClient
698 // based on device version reported by the HAL.
699 switch(deviceVersion) {
700 case CAMERA_DEVICE_API_VERSION_1_0:
701 if (effectiveApiLevel == API_1) { // Camera1 API route
702 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
703 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
704 clientPid, clientUid, getpid(), legacyMode);
705 } else { // Camera2 API route
706 ALOGW("Camera using old HAL version: %d", deviceVersion);
707 return -EOPNOTSUPP;
708 }
709 break;
710 case CAMERA_DEVICE_API_VERSION_2_0:
711 case CAMERA_DEVICE_API_VERSION_2_1:
712 case CAMERA_DEVICE_API_VERSION_3_0:
713 case CAMERA_DEVICE_API_VERSION_3_1:
714 case CAMERA_DEVICE_API_VERSION_3_2:
715 case CAMERA_DEVICE_API_VERSION_3_3:
716 if (effectiveApiLevel == API_1) { // Camera1 API route
717 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
718 *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
719 clientPid, clientUid, servicePid, legacyMode);
720 } else { // Camera2 API route
721 sp<ICameraDeviceCallbacks> tmp =
722 static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
723 *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
724 facing, clientPid, clientUid, servicePid);
725 }
726 break;
727 default:
728 // Should not be reachable
729 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
730 return INVALID_OPERATION;
731 }
732 } else {
733 // A particular HAL version is requested by caller. Create CameraClient
734 // based on the requested HAL version.
735 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
736 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
737 // Only support higher HAL version device opened as HAL1.0 device.
738 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
739 *client = new CameraClient(cameraService, tmp, packageName, id, facing,
740 clientPid, clientUid, servicePid, legacyMode);
741 } else {
742 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
743 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
744 " opened as HAL %x device", halVersion, deviceVersion,
745 CAMERA_DEVICE_API_VERSION_1_0);
746 return INVALID_OPERATION;
747 }
748 }
749 return NO_ERROR;
750}
751
Ruben Brunk6267b532015-04-30 17:44:07 -0700752String8 CameraService::toString(std::set<userid_t> intSet) {
753 String8 s("");
754 bool first = true;
755 for (userid_t i : intSet) {
756 if (first) {
757 s.appendFormat("%d", i);
758 first = false;
759 } else {
760 s.appendFormat(", %d", i);
761 }
762 }
763 return s;
764}
765
Ruben Brunkcc776712015-02-17 20:18:47 -0800766status_t CameraService::initializeShimMetadata(int cameraId) {
767 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700768
769 String16 internalPackageName("media");
Ruben Brunkcc776712015-02-17 20:18:47 -0800770 String8 id = String8::format("%d", cameraId);
771 status_t ret = NO_ERROR;
772 sp<Client> tmp = nullptr;
773 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
774 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1,
775 false, true, tmp)) != NO_ERROR) {
776 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
777 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700778 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800779 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700780}
781
Igor Murashkin65d14b92014-06-17 12:03:20 -0700782status_t CameraService::getLegacyParametersLazy(int cameraId,
783 /*out*/
784 CameraParameters* parameters) {
785
786 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
787
788 status_t ret = 0;
789
790 if (parameters == NULL) {
791 ALOGE("%s: parameters must not be null", __FUNCTION__);
792 return BAD_VALUE;
793 }
794
Ruben Brunkcc776712015-02-17 20:18:47 -0800795 String8 id = String8::format("%d", cameraId);
796
797 // Check if we already have parameters
798 {
799 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700800 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800801 auto cameraState = getCameraState(id);
802 if (cameraState == nullptr) {
803 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
804 return BAD_VALUE;
805 }
806 CameraParameters p = cameraState->getShimParams();
807 if (!p.isEmpty()) {
808 *parameters = p;
809 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700810 }
811 }
812
Ruben Brunkcc776712015-02-17 20:18:47 -0800813 int64_t token = IPCThreadState::self()->clearCallingIdentity();
814 ret = initializeShimMetadata(cameraId);
815 IPCThreadState::self()->restoreCallingIdentity(token);
816 if (ret != NO_ERROR) {
817 // Error already logged by callee
818 return ret;
819 }
820
821 // Check for parameters again
822 {
823 // Scope for service lock
824 Mutex::Autolock lock(mServiceLock);
825 auto cameraState = getCameraState(id);
826 if (cameraState == nullptr) {
827 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
828 return BAD_VALUE;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700829 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 CameraParameters p = cameraState->getShimParams();
831 if (!p.isEmpty()) {
832 *parameters = p;
833 return NO_ERROR;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700834 }
835 }
836
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
838 __FUNCTION__);
839 return INVALID_OPERATION;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700840}
841
Ruben Brunk36597b22015-03-20 22:15:57 -0700842status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
843 const {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800844
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 int callingPid = getCallingPid();
Tyler Luu5861a9a2011-10-06 00:00:03 -0500846
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800847 if (clientUid == USE_CALLING_UID) {
848 clientUid = getCallingUid();
849 } else {
850 // We only trust our own process to forward client UIDs
851 if (callingPid != getpid()) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700852 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
853 callingPid, clientUid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700854 return PERMISSION_DENIED;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800855 }
856 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857
Iliyan Malchev8951a972011-04-14 16:55:59 -0700858 if (!mModule) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800859 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
860 callingPid);
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700861 return -ENODEV;
Iliyan Malchev8951a972011-04-14 16:55:59 -0700862 }
863
Ruben Brunkcc776712015-02-17 20:18:47 -0800864 if (getCameraState(cameraId) == nullptr) {
865 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
866 cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700867 return -ENODEV;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 }
869
Ruben Brunkcc776712015-02-17 20:18:47 -0800870 // Check device policy for this camera
Wu-cheng Lia3355432011-05-20 14:54:25 +0800871 char value[PROPERTY_VALUE_MAX];
Amith Yamasani228711d2015-02-13 13:25:39 -0800872 char key[PROPERTY_KEY_MAX];
Ruben Brunk6267b532015-04-30 17:44:07 -0700873 userid_t clientUserId = multiuser_get_user_id(clientUid);
Amith Yamasani228711d2015-02-13 13:25:39 -0800874 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
875 property_get(key, value, "0");
Wu-cheng Lia3355432011-05-20 14:54:25 +0800876 if (strcmp(value, "1") == 0) {
877 // Camera is disabled by DevicePolicyManager.
Ruben Brunkcc776712015-02-17 20:18:47 -0800878 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
879 "policy)", callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700880 return -EACCES;
Wu-cheng Lia3355432011-05-20 14:54:25 +0800881 }
882
Ruben Brunka8ca9152015-04-07 14:23:40 -0700883 // Only allow clients who are being used by the current foreground device user, unless calling
884 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700885 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
886 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
887 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
888 toString(mAllowedUsers).string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700889 return PERMISSION_DENIED;
890 }
891
Ruben Brunkcc776712015-02-17 20:18:47 -0800892 return checkIfDeviceIsUsable(cameraId);
893}
894
895status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
896 auto cameraState = getCameraState(cameraId);
897 int callingPid = getCallingPid();
898 if (cameraState == nullptr) {
899 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
900 cameraId.string());
901 return -ENODEV;
902 }
903
904 ICameraServiceListener::Status currentStatus = cameraState->getStatus();
Igor Murashkincba2c162013-03-20 15:56:31 -0700905 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800906 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
907 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700908 return -ENODEV;
Igor Murashkincba2c162013-03-20 15:56:31 -0700909 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800910 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
911 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700912 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700913 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700914
Ruben Brunkcc776712015-02-17 20:18:47 -0800915 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800916}
917
Ruben Brunkcc776712015-02-17 20:18:47 -0800918void CameraService::finishConnectLocked(const sp<BasicClient>& client,
919 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800920
Ruben Brunkcc776712015-02-17 20:18:47 -0800921 // Make a descriptor for the incoming client
922 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
923 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
924
925 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
926 String8(client->getPackageName()));
927
928 if (evicted.size() > 0) {
929 // This should never happen - clients should already have been removed in disconnect
930 for (auto& i : evicted) {
931 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
932 __FUNCTION__, i->getKey().string());
933 }
934
935 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
936 __FUNCTION__);
937 }
938}
939
940status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
941 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
942 /*out*/
943 sp<BasicClient>* client,
944 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
945
946 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -0700947 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -0800948 DescriptorPtr clientDescriptor;
949 {
950 if (effectiveApiLevel == API_1) {
951 // If we are using API1, any existing client for this camera ID with the same remote
952 // should be returned rather than evicted to allow MediaRecorder to work properly.
953
954 auto current = mActiveClientManager.get(cameraId);
955 if (current != nullptr) {
956 auto clientSp = current->getValue();
957 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700958 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
959 ALOGW("CameraService connect called from same client, but with a different"
960 " API level, evicting prior client...");
961 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800962 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700963 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800964 *client = clientSp;
965 return NO_ERROR;
966 }
967 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800968 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -0800969 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +0800970
Ruben Brunkcc776712015-02-17 20:18:47 -0800971 // Return error if the device was unplugged or removed by the HAL for some reason
972 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
973 return ret;
974 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800975
Ruben Brunkcc776712015-02-17 20:18:47 -0800976 // Get current active client PIDs
977 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
978 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800979
Chih-Hung Hsieh54b42462015-03-19 12:04:54 -0700980 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
981 // address of PROCESS_STATE_NONEXISTENT as a reference argument
982 // for the vector constructor. PROCESS_STATE_NONEXISTENT does
983 // not have an out-of-class definition.
984 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800985
Ruben Brunkcc776712015-02-17 20:18:47 -0800986 // Get priorites of all active PIDs
987 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
988 /*out*/&priorities[0]);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700989
Ruben Brunkcc776712015-02-17 20:18:47 -0800990 // Update all active clients' priorities
991 std::map<int,int> pidToPriorityMap;
992 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
993 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
994 }
995 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800996
Ruben Brunkcc776712015-02-17 20:18:47 -0800997 // Get state for the given cameraId
998 auto state = getCameraState(cameraId);
999 if (state == nullptr) {
1000 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1001 clientPid, cameraId.string());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001002 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001003 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001004
1005 // Make descriptor for incoming client
1006 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1007 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1008 state->getConflicting(),
1009 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1010
1011 // Find clients that would be evicted
1012 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1013
1014 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1015 // background, so we cannot do evictions
1016 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1017 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1018 " priority).", clientPid);
1019
1020 sp<BasicClient> clientSp = clientDescriptor->getValue();
1021 String8 curTime = getFormattedCurrentTime();
1022 auto incompatibleClients =
1023 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1024
1025 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Ruben Brunka8ca9152015-04-07 14:23:40 -07001026 "(PID %d, priority %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001027 cameraId.string(), packageName.string(), clientPid,
1028 getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1029
1030 for (auto& i : incompatibleClients) {
1031 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1032 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1033 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1034 i->getPriority());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001035 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1036 PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1037 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1038 i->getPriority());
Ruben Brunkcc776712015-02-17 20:18:47 -08001039 }
1040
1041 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001042 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001043 mEventLog.add(msg);
1044
1045 return -EBUSY;
1046 }
1047
1048 for (auto& i : evicted) {
1049 sp<BasicClient> clientSp = i->getValue();
1050 if (clientSp.get() == nullptr) {
1051 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1052
1053 // TODO: Remove this
1054 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1055 __FUNCTION__);
1056 mActiveClientManager.remove(i);
1057 continue;
1058 }
1059
1060 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1061 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001062 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001063
Ruben Brunkcc776712015-02-17 20:18:47 -08001064 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001065 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1066 " %" PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for"
1067 " package %s (PID %d, priority %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001068 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1069 i->getOwnerId(), i->getPriority(), cameraId.string(),
1070 packageName.string(), clientPid,
1071 getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1072
1073 // Notify the client of disconnection
1074 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1075 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001076 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001077 }
1078
Ruben Brunkcc776712015-02-17 20:18:47 -08001079 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1080 // other clients from connecting in mServiceLockWrapper if held
1081 mServiceLock.unlock();
1082
1083 // Clear caller identity temporarily so client disconnect PID checks work correctly
1084 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1085
1086 // Destroy evicted clients
1087 for (auto& i : evictedClients) {
1088 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001089 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001090 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001091
1092 IPCThreadState::self()->restoreCallingIdentity(token);
1093
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001094 for (const auto& i : evictedClients) {
1095 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1096 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1097 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1098 if (ret == TIMED_OUT) {
1099 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1100 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1101 mActiveClientManager.toString().string());
1102 return -EBUSY;
1103 }
1104 if (ret != NO_ERROR) {
1105 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1106 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1107 ret, mActiveClientManager.toString().string());
1108 return ret;
1109 }
1110 }
1111
1112 evictedClients.clear();
1113
Ruben Brunkcc776712015-02-17 20:18:47 -08001114 // Once clients have been disconnected, relock
1115 mServiceLock.lock();
1116
1117 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1118 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1119 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001120 }
1121
Ruben Brunkcc776712015-02-17 20:18:47 -08001122 *partial = clientDescriptor;
1123 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001124}
1125
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001126status_t CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001127 const sp<ICameraClient>& cameraClient,
1128 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001129 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001130 int clientUid,
1131 /*out*/
1132 sp<ICamera>& device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001133
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 status_t ret = NO_ERROR;
1135 String8 id = String8::format("%d", cameraId);
1136 sp<Client> client = nullptr;
1137 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001138 clientPackageName, clientUid, API_1, false, false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001139
Ruben Brunkcc776712015-02-17 20:18:47 -08001140 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001141 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001142 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144 }
1145
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001146 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001147 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148}
1149
Zhijun Heb10cdad2014-06-16 16:38:35 -07001150status_t CameraService::connectLegacy(
1151 const sp<ICameraClient>& cameraClient,
1152 int cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001153 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001154 int clientUid,
1155 /*out*/
1156 sp<ICamera>& device) {
1157
Ruben Brunka8ca9152015-04-07 14:23:40 -07001158 String8 id = String8::format("%d", cameraId);
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08001159 int apiVersion = mModule->getModuleApiVersion();
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001160 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001161 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
Igor Murashkin3d07d1a2014-06-20 11:27:03 -07001162 /*
1163 * Either the HAL version is unspecified in which case this just creates
1164 * a camera client selected by the latest device version, or
1165 * it's a particular version in which case the HAL must supported
1166 * the open_legacy call
1167 */
Zhijun Heb10cdad2014-06-16 16:38:35 -07001168 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
Yin-Chia Yehe074a932015-01-30 10:29:02 -08001169 __FUNCTION__, apiVersion);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001170 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001171 String8("HAL module version doesn't support legacy HAL connections"));
Zhijun Heb10cdad2014-06-16 16:38:35 -07001172 return INVALID_OPERATION;
1173 }
1174
Ruben Brunkcc776712015-02-17 20:18:47 -08001175 status_t ret = NO_ERROR;
Ruben Brunkcc776712015-02-17 20:18:47 -08001176 sp<Client> client = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001177 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 clientUid, API_1, true, false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001179
Ruben Brunkcc776712015-02-17 20:18:47 -08001180 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001181 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001182 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001183 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001184 }
1185
Zhijun Heb10cdad2014-06-16 16:38:35 -07001186 device = client;
Ruben Brunkcc776712015-02-17 20:18:47 -08001187 return NO_ERROR;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001188}
1189
Ruben Brunkcc776712015-02-17 20:18:47 -08001190status_t CameraService::connectDevice(
1191 const sp<ICameraDeviceCallbacks>& cameraCb,
1192 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001193 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001194 int clientUid,
1195 /*out*/
1196 sp<ICameraDeviceUser>& device) {
1197
1198 status_t ret = NO_ERROR;
1199 String8 id = String8::format("%d", cameraId);
1200 sp<CameraDeviceClient> client = nullptr;
1201 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001202 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
Ruben Brunkcc776712015-02-17 20:18:47 -08001203 /*out*/client);
1204
1205 if(ret != NO_ERROR) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001206 logRejected(id, getCallingPid(), String8(clientPackageName),
Ruben Brunka8ca9152015-04-07 14:23:40 -07001207 String8::format("%s (%d)", strerror(-ret), ret));
Ruben Brunkcc776712015-02-17 20:18:47 -08001208 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001209 }
1210
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 device = client;
1212 return NO_ERROR;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001213}
1214
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001215status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1216 const sp<IBinder>& clientBinder) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001217 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001218 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001219 return -EINVAL;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001220 }
1221
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001222 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001223 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001224
1225 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001226 auto state = getCameraState(id);
1227 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001228 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001229 return -EINVAL;
1230 }
1231
1232 ICameraServiceListener::Status cameraStatus = state->getStatus();
1233 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1234 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001235 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001236 return -EINVAL;
1237 }
1238
1239 {
1240 Mutex::Autolock al(mTorchStatusMutex);
1241 ICameraServiceListener::TorchStatus status;
1242 status_t res = getTorchStatusLocked(id, &status);
1243 if (res) {
1244 ALOGE("%s: getting current torch status failed for camera %s",
1245 __FUNCTION__, id.string());
1246 return -EINVAL;
1247 }
1248
1249 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001250 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001251 ALOGE("%s: torch mode of camera %s is not available because "
1252 "camera is in use", __FUNCTION__, id.string());
1253 return -EBUSY;
1254 } else {
1255 ALOGE("%s: torch mode of camera %s is not available due to "
1256 "insufficient resources", __FUNCTION__, id.string());
1257 return -EUSERS;
1258 }
1259 }
1260 }
1261
Ruben Brunk99e69712015-05-26 17:25:07 -07001262 {
1263 // Update UID map - this is used in the torch status changed callbacks, so must be done
1264 // before setTorchMode
1265 Mutex::Autolock al(mTorchClientMapMutex);
1266 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1267 mTorchUidMap[id].first = uid;
1268 mTorchUidMap[id].second = uid;
1269 } else {
1270 // Set the pending UID
1271 mTorchUidMap[id].first = uid;
1272 }
1273 }
1274
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001275 status_t res = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001276
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001277 if (res) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001278 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1279 __FUNCTION__, id.string(), enabled, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001280 return res;
1281 }
1282
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001283 {
1284 // update the link to client's death
1285 Mutex::Autolock al(mTorchClientMapMutex);
1286 ssize_t index = mTorchClientMap.indexOfKey(id);
Ruben Brunk99e69712015-05-26 17:25:07 -07001287 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001288 if (enabled) {
1289 if (index == NAME_NOT_FOUND) {
1290 mTorchClientMap.add(id, clientBinder);
1291 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001292 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001293 mTorchClientMap.replaceValueAt(index, clientBinder);
1294 }
1295 clientBinder->linkToDeath(this);
1296 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001297 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001298 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001299 }
1300
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001301 return OK;
1302}
1303
Ruben Brunk6267b532015-04-30 17:44:07 -07001304void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001305 switch(eventId) {
1306 case ICameraService::USER_SWITCHED: {
Ruben Brunk6267b532015-04-30 17:44:07 -07001307 doUserSwitch(/*newUserIds*/args, /*length*/length);
Ruben Brunk36597b22015-03-20 22:15:57 -07001308 break;
1309 }
1310 case ICameraService::NO_EVENT:
1311 default: {
1312 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1313 eventId);
1314 break;
1315 }
1316 }
1317}
1318
Ruben Brunk99e69712015-05-26 17:25:07 -07001319status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001320 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001321
Ruben Brunk3450ba72015-06-16 11:00:37 -07001322 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001323 ALOGE("%s: Listener must not be null", __FUNCTION__);
1324 return BAD_VALUE;
1325 }
1326
Igor Murashkinbfc99152013-02-27 12:55:20 -08001327 Mutex::Autolock lock(mServiceLock);
1328
Ruben Brunkcc776712015-02-17 20:18:47 -08001329 {
1330 Mutex::Autolock lock(mStatusListenerLock);
1331 for (auto& it : mListenerList) {
1332 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1333 ALOGW("%s: Tried to add listener %p which was already subscribed",
1334 __FUNCTION__, listener.get());
1335 return ALREADY_EXISTS;
1336 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001337 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001338
1339 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001340 }
1341
Igor Murashkinbfc99152013-02-27 12:55:20 -08001342
Igor Murashkincba2c162013-03-20 15:56:31 -07001343 /* Immediately signal current status to this listener only */
1344 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001345 Mutex::Autolock lock(mCameraStatesLock);
1346 for (auto& i : mCameraStates) {
1347 // TODO: Update binder to use String16 for camera IDs and remove;
1348 int id = cameraIdToInt(i.first);
1349 if (id == -1) continue;
1350
1351 listener->onStatusChanged(i.second->getStatus(), id);
Igor Murashkincba2c162013-03-20 15:56:31 -07001352 }
1353 }
1354
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001355 /* Immediately signal current torch status to this listener only */
1356 {
1357 Mutex::Autolock al(mTorchStatusMutex);
1358 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001359 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1360 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001361 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001362 }
1363
Igor Murashkinbfc99152013-02-27 12:55:20 -08001364 return OK;
1365}
Ruben Brunkcc776712015-02-17 20:18:47 -08001366
1367status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Igor Murashkinbfc99152013-02-27 12:55:20 -08001368 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1369
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001370 if (listener == 0) {
1371 ALOGE("%s: Listener must not be null", __FUNCTION__);
1372 return BAD_VALUE;
1373 }
1374
Igor Murashkinbfc99152013-02-27 12:55:20 -08001375 Mutex::Autolock lock(mServiceLock);
1376
Ruben Brunkcc776712015-02-17 20:18:47 -08001377 {
1378 Mutex::Autolock lock(mStatusListenerLock);
1379 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1380 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1381 mListenerList.erase(it);
1382 return OK;
1383 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001384 }
1385 }
1386
1387 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1388 __FUNCTION__, listener.get());
1389
1390 return BAD_VALUE;
Igor Murashkin634a5152013-02-20 17:15:11 -08001391}
1392
Ruben Brunkcc776712015-02-17 20:18:47 -08001393status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001394 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1395
1396 if (parameters == NULL) {
1397 ALOGE("%s: parameters must not be null", __FUNCTION__);
1398 return BAD_VALUE;
1399 }
1400
1401 status_t ret = 0;
1402
1403 CameraParameters shimParams;
1404 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1405 // Error logged by caller
1406 return ret;
1407 }
1408
1409 String8 shimParamsString8 = shimParams.flatten();
1410 String16 shimParamsString16 = String16(shimParamsString8);
1411
1412 *parameters = shimParamsString16;
1413
1414 return OK;
1415}
1416
1417status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1418 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1419
1420 switch (apiVersion) {
1421 case API_VERSION_1:
1422 case API_VERSION_2:
1423 break;
1424 default:
1425 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1426 return BAD_VALUE;
1427 }
1428
1429 int facing = -1;
1430 int deviceVersion = getDeviceVersion(cameraId, &facing);
1431
1432 switch(deviceVersion) {
1433 case CAMERA_DEVICE_API_VERSION_1_0:
1434 case CAMERA_DEVICE_API_VERSION_2_0:
1435 case CAMERA_DEVICE_API_VERSION_2_1:
1436 case CAMERA_DEVICE_API_VERSION_3_0:
1437 case CAMERA_DEVICE_API_VERSION_3_1:
1438 if (apiVersion == API_VERSION_2) {
1439 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1440 __FUNCTION__, cameraId);
1441 return -EOPNOTSUPP;
1442 } else { // if (apiVersion == API_VERSION_1) {
1443 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1444 __FUNCTION__, cameraId);
1445 return OK;
1446 }
1447 case CAMERA_DEVICE_API_VERSION_3_2:
Ruben Brunkcc776712015-02-17 20:18:47 -08001448 case CAMERA_DEVICE_API_VERSION_3_3:
Igor Murashkin65d14b92014-06-17 12:03:20 -07001449 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1450 __FUNCTION__, cameraId);
1451 return OK;
1452 case -1:
1453 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1454 return BAD_VALUE;
1455 default:
1456 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1457 return INVALID_OPERATION;
1458 }
1459
1460 return OK;
1461}
1462
Ruben Brunkcc776712015-02-17 20:18:47 -08001463void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001464 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001465 for (auto& i : mActiveClientManager.getAll()) {
1466 auto clientSp = i->getValue();
1467 if (clientSp.get() == client) {
1468 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001469 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001470 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001471}
1472
Ruben Brunkcc776712015-02-17 20:18:47 -08001473bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1474 const int callingPid = getCallingPid();
1475 const int servicePid = getpid();
1476 bool ret = false;
1477 {
1478 // Acquire mServiceLock and prevent other clients from connecting
1479 std::unique_ptr<AutoConditionLock> lock =
1480 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001481
Igor Murashkin634a5152013-02-20 17:15:11 -08001482
Ruben Brunkcc776712015-02-17 20:18:47 -08001483 std::vector<sp<BasicClient>> evicted;
1484 for (auto& i : mActiveClientManager.getAll()) {
1485 auto clientSp = i->getValue();
1486 if (clientSp.get() == nullptr) {
1487 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1488 mActiveClientManager.remove(i);
1489 continue;
1490 }
1491 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1492 callingPid == clientSp->getClientPid())) {
1493 mActiveClientManager.remove(i);
1494 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001495
Ruben Brunkcc776712015-02-17 20:18:47 -08001496 // Notify the client of disconnection
1497 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1498 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001499 }
1500 }
1501
Ruben Brunkcc776712015-02-17 20:18:47 -08001502 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1503 // other clients from connecting in mServiceLockWrapper if held
1504 mServiceLock.unlock();
1505
Ruben Brunk36597b22015-03-20 22:15:57 -07001506 // Do not clear caller identity, remote caller should be client proccess
1507
Ruben Brunkcc776712015-02-17 20:18:47 -08001508 for (auto& i : evicted) {
1509 if (i.get() != nullptr) {
1510 i->disconnect();
1511 ret = true;
1512 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001513 }
1514
Ruben Brunkcc776712015-02-17 20:18:47 -08001515 // Reacquire mServiceLock
1516 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001517
Ruben Brunkcc776712015-02-17 20:18:47 -08001518 } // lock is destroyed, allow further connect calls
1519
1520 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001521}
1522
Igor Murashkinecf17e82012-10-02 16:05:11 -07001523
Eino-Ville Talvalabad43582015-08-14 13:12:32 -07001524/**
1525 * Check camera capabilities, such as support for basic color operation
1526 */
1527int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1528
1529 // Assume all devices pre-v3.3 are backward-compatible
1530 bool isBackwardCompatible = true;
1531 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1532 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1533 isBackwardCompatible = false;
1534 status_t res;
1535 camera_metadata_ro_entry_t caps;
1536 res = find_camera_metadata_ro_entry(
1537 info.static_camera_characteristics,
1538 ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1539 &caps);
1540 if (res != 0) {
1541 ALOGW("%s: Unable to find camera capabilities for camera device %d",
1542 __FUNCTION__, id);
1543 caps.count = 0;
1544 }
1545 for (size_t i = 0; i < caps.count; i++) {
1546 if (caps.data.u8[i] ==
1547 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1548 isBackwardCompatible = true;
1549 break;
1550 }
1551 }
1552 }
1553
1554 if (!isBackwardCompatible) {
1555 mNumberOfNormalCameras--;
1556 *latestStrangeCameraId = id;
1557 } else {
1558 if (id > *latestStrangeCameraId) {
1559 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1560 "This is not allowed due backward-compatibility requirements",
1561 __FUNCTION__, id, *latestStrangeCameraId);
1562 logServiceError("Invalid order of camera devices", ENODEV);
1563 mNumberOfCameras = 0;
1564 mNumberOfNormalCameras = 0;
1565 return INVALID_OPERATION;
1566 }
1567 }
1568 return OK;
1569}
1570
Ruben Brunkcc776712015-02-17 20:18:47 -08001571std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1572 const String8& cameraId) const {
1573 std::shared_ptr<CameraState> state;
1574 {
1575 Mutex::Autolock lock(mCameraStatesLock);
1576 auto iter = mCameraStates.find(cameraId);
1577 if (iter != mCameraStates.end()) {
1578 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 }
1580 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001581 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582}
1583
Ruben Brunkcc776712015-02-17 20:18:47 -08001584sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1585 // Remove from active clients list
1586 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1587 if (clientDescriptorPtr == nullptr) {
1588 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1589 cameraId.string());
1590 return sp<BasicClient>{nullptr};
1591 }
1592
1593 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001594}
1595
Ruben Brunk6267b532015-04-30 17:44:07 -07001596void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001597 // Acquire mServiceLock and prevent other clients from connecting
1598 std::unique_ptr<AutoConditionLock> lock =
1599 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1600
Ruben Brunk6267b532015-04-30 17:44:07 -07001601 std::set<userid_t> newAllowedUsers;
1602 for (size_t i = 0; i < length; i++) {
1603 if (newUserId[i] < 0) {
1604 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1605 __FUNCTION__, newUserId[i]);
1606 return;
1607 }
1608 newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001609 }
1610
Ruben Brunka8ca9152015-04-07 14:23:40 -07001611
Ruben Brunk6267b532015-04-30 17:44:07 -07001612 if (newAllowedUsers == mAllowedUsers) {
1613 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1614 return;
1615 }
1616
1617 logUserSwitch(mAllowedUsers, newAllowedUsers);
1618
1619 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001620
1621 // Current user has switched, evict all current clients.
1622 std::vector<sp<BasicClient>> evicted;
1623 for (auto& i : mActiveClientManager.getAll()) {
1624 auto clientSp = i->getValue();
1625
1626 if (clientSp.get() == nullptr) {
1627 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1628 continue;
1629 }
1630
Ruben Brunk6267b532015-04-30 17:44:07 -07001631 // Don't evict clients that are still allowed.
1632 uid_t clientUid = clientSp->getClientUid();
1633 userid_t clientUserId = multiuser_get_user_id(clientUid);
1634 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1635 continue;
1636 }
1637
Ruben Brunk36597b22015-03-20 22:15:57 -07001638 evicted.push_back(clientSp);
1639
1640 String8 curTime = getFormattedCurrentTime();
1641
1642 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1643 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001644
Ruben Brunk36597b22015-03-20 22:15:57 -07001645 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001646 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Ruben Brunk36597b22015-03-20 22:15:57 -07001647 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
Ruben Brunka8ca9152015-04-07 14:23:40 -07001648 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1649 i->getOwnerId(), i->getPriority()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001650
1651 }
1652
1653 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1654 // blocking other clients from connecting in mServiceLockWrapper if held.
1655 mServiceLock.unlock();
1656
1657 // Clear caller identity temporarily so client disconnect PID checks work correctly
1658 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1659
1660 for (auto& i : evicted) {
1661 i->disconnect();
1662 }
1663
1664 IPCThreadState::self()->restoreCallingIdentity(token);
1665
1666 // Reacquire mServiceLock
1667 mServiceLock.lock();
1668}
Ruben Brunkcc776712015-02-17 20:18:47 -08001669
Ruben Brunka8ca9152015-04-07 14:23:40 -07001670void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001672 Mutex::Autolock l(mLogLock);
1673 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674}
1675
Ruben Brunka8ca9152015-04-07 14:23:40 -07001676void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001677 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001679 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001680 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001681}
1682
1683void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001684 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001685 // Log the clients evicted
1686 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001687 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001688}
1689
1690void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001691 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001692 // Log the client rejected
1693 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001694 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001695}
1696
Ruben Brunk6267b532015-04-30 17:44:07 -07001697void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1698 const std::set<userid_t>& newUserIds) {
1699 String8 newUsers = toString(newUserIds);
1700 String8 oldUsers = toString(oldUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -07001701 // Log the new and old users
Ruben Brunk6267b532015-04-30 17:44:07 -07001702 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1703 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001704}
1705
1706void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1707 // Log the device removal
1708 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1709}
1710
1711void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1712 // Log the device removal
1713 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1714}
1715
1716void CameraService::logClientDied(int clientPid, const char* reason) {
1717 // Log the device removal
1718 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001719}
1720
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07001721void CameraService::logServiceError(const char* msg, int errorCode) {
1722 String8 curTime = getFormattedCurrentTime();
1723 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1724}
1725
Ruben Brunk36597b22015-03-20 22:15:57 -07001726status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1727 uint32_t flags) {
1728
1729 const int pid = getCallingPid();
1730 const int selfPid = getpid();
1731
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 // Permission checks
1733 switch (code) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001734 case BnCameraService::CONNECT:
1735 case BnCameraService::CONNECT_DEVICE:
1736 case BnCameraService::CONNECT_LEGACY: {
1737 if (pid != selfPid) {
1738 // we're called from a different process, do the real check
1739 if (!checkCallingPermission(
1740 String16("android.permission.CAMERA"))) {
1741 const int uid = getCallingUid();
1742 ALOGE("Permission Denial: "
1743 "can't use the camera pid=%d, uid=%d", pid, uid);
1744 return PERMISSION_DENIED;
1745 }
1746 }
1747 break;
1748 }
Ruben Brunk36597b22015-03-20 22:15:57 -07001749 case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1750 if (pid != selfPid) {
1751 // Ensure we're being called by system_server, or similar process with
1752 // permissions to notify the camera service about system events
1753 if (!checkCallingPermission(
1754 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1755 const int uid = getCallingUid();
1756 ALOGE("Permission Denial: cannot send updates to camera service about system"
1757 " events from pid=%d, uid=%d", pid, uid);
1758 return PERMISSION_DENIED;
1759 }
1760 }
1761 break;
1762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 }
1764
1765 return BnCameraService::onTransact(code, data, reply, flags);
1766}
1767
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768// We share the media players for shutter and recording sound for all clients.
1769// A reference count is kept to determine when we will actually release the
1770// media players.
1771
Chih-Chung Changff4f55c2011-10-17 19:03:12 +08001772MediaPlayer* CameraService::newMediaPlayer(const char *file) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 MediaPlayer* mp = new MediaPlayer();
Andreas Huber1b86fe02014-01-29 11:13:26 -08001774 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08001775 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 mp->prepare();
1777 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001778 ALOGE("Failed to load CameraService sounds: %s", file);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 return NULL;
1780 }
1781 return mp;
1782}
1783
1784void CameraService::loadSound() {
1785 Mutex::Autolock lock(mSoundLock);
1786 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1787 if (mSoundRef++) return;
1788
1789 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1790 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1791}
1792
1793void CameraService::releaseSound() {
1794 Mutex::Autolock lock(mSoundLock);
1795 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1796 if (--mSoundRef) return;
1797
1798 for (int i = 0; i < NUM_SOUNDS; i++) {
1799 if (mSoundPlayer[i] != 0) {
1800 mSoundPlayer[i]->disconnect();
1801 mSoundPlayer[i].clear();
1802 }
1803 }
1804}
1805
1806void CameraService::playSound(sound_kind kind) {
1807 LOG1("playSound(%d)", kind);
1808 Mutex::Autolock lock(mSoundLock);
1809 sp<MediaPlayer> player = mSoundPlayer[kind];
1810 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08001811 player->seekTo(0);
1812 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 }
1814}
1815
1816// ----------------------------------------------------------------------------
1817
1818CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07001819 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001820 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001821 int cameraId, int cameraFacing,
1822 int clientPid, uid_t clientUid,
1823 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001824 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08001825 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001826 clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001827 cameraId, cameraFacing,
1828 clientPid, clientUid,
1829 servicePid)
Igor Murashkin634a5152013-02-20 17:15:11 -08001830{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 int callingPid = getCallingPid();
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001832 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001834 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 cameraService->loadSound();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001837
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001838 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839}
1840
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841// tear down the client
1842CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001843 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08001844 mDestructionStarted = true;
1845
Eino-Ville Talvalaf69c70d2012-05-20 15:59:14 -07001846 mCameraService->releaseSound();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07001847 // unconditionally disconnect. function is idempotent
1848 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849}
1850
Igor Murashkin634a5152013-02-20 17:15:11 -08001851CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001852 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001853 const String16& clientPackageName,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001854 int cameraId, int cameraFacing,
1855 int clientPid, uid_t clientUid,
1856 int servicePid):
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001857 mClientPackageName(clientPackageName), mDisconnected(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08001858{
1859 mCameraService = cameraService;
Igor Murashkin44cfcf02013-03-01 16:22:28 -08001860 mRemoteBinder = remoteCallback;
Igor Murashkin634a5152013-02-20 17:15:11 -08001861 mCameraId = cameraId;
1862 mCameraFacing = cameraFacing;
1863 mClientPid = clientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001864 mClientUid = clientUid;
Igor Murashkin634a5152013-02-20 17:15:11 -08001865 mServicePid = servicePid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001866 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08001867 mDestructionStarted = false;
1868}
1869
1870CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07001871 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08001872 mDestructionStarted = true;
1873}
1874
1875void CameraService::BasicClient::disconnect() {
Ruben Brunk36597b22015-03-20 22:15:57 -07001876 if (mDisconnected) {
1877 ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1878 mCameraId);
1879 return;
1880 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001881 mDisconnected = true;;
1882
1883 mCameraService->removeByClient(this);
1884 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001885 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08001886
1887 sp<IBinder> remote = getRemote();
1888 if (remote != nullptr) {
1889 remote->unlinkToDeath(mCameraService);
1890 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001891
1892 finishCameraOps();
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1894
Igor Murashkincba2c162013-03-20 15:56:31 -07001895 // client shouldn't be able to call into us anymore
1896 mClientPid = 0;
Igor Murashkin634a5152013-02-20 17:15:11 -08001897}
1898
Ruben Brunkcc776712015-02-17 20:18:47 -08001899String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001900 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08001901}
1902
1903
1904int CameraService::BasicClient::getClientPid() const {
1905 return mClientPid;
1906}
1907
Ruben Brunk6267b532015-04-30 17:44:07 -07001908uid_t CameraService::BasicClient::getClientUid() const {
1909 return mClientUid;
1910}
1911
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001912bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1913 // Defaults to API2.
1914 return level == API_2;
1915}
1916
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001917status_t CameraService::BasicClient::startCameraOps() {
1918 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001919 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001920 mOpsCallback = new OpsCallback(this);
1921
Igor Murashkine6800ce2013-03-04 17:25:57 -08001922 {
1923 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001924 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001925 }
1926
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001927 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001928 mClientPackageName, mOpsCallback);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001929 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001930 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001931
Svetoslav28e8ef72015-05-11 19:21:31 -07001932 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001933 ALOGI("Camera %d: Access for \"%s\" has been revoked",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001934 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001935 return PERMISSION_DENIED;
1936 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001937
Svetoslav28e8ef72015-05-11 19:21:31 -07001938 if (res == AppOpsManager::MODE_IGNORED) {
1939 ALOGI("Camera %d: Access for \"%s\" has been restricted",
1940 mCameraId, String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07001941 // Return the same error as for device policy manager rejection
1942 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07001943 }
1944
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001945 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001946
1947 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1948 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
Ruben Brunkcc776712015-02-17 20:18:47 -08001949 String8::format("%d", mCameraId));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001950
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001951 return OK;
1952}
1953
1954status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001955 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001956 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001957 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001958 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001959 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001960 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001961
Ruben Brunkcc776712015-02-17 20:18:47 -08001962 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1963 ICameraServiceListener::STATUS_ENUMERATING};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001964
Ruben Brunkcc776712015-02-17 20:18:47 -08001965 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001966 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
Ruben Brunkcc776712015-02-17 20:18:47 -08001967 String8::format("%d", mCameraId), rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001968
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001969 // Notify flashlight that a camera device is closed.
1970 mCameraService->mFlashlight->deviceClosed(
1971 String8::format("%d", mCameraId));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001972 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001973 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08001974 if (mOpsCallback != NULL) {
1975 mAppOpsManager.stopWatchingMode(mOpsCallback);
1976 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001977 mOpsCallback.clear();
1978
1979 return OK;
1980}
1981
1982void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1983 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001984 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001985
1986 if (op != AppOpsManager::OP_CAMERA) {
1987 ALOGW("Unexpected app ops notification received: %d", op);
1988 return;
1989 }
1990
1991 int32_t res;
1992 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001993 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08001994 ALOGV("checkOp returns: %d, %s ", res,
1995 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1996 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1997 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1998 "UNKNOWN");
1999
2000 if (res != AppOpsManager::MODE_ALLOWED) {
2001 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2002 myName.string());
2003 // Reset the client PID to allow server-initiated disconnect,
2004 // and to prevent further calls by client.
2005 mClientPid = getCallingPid();
Jianing Weicb0652e2014-03-12 18:29:36 -07002006 CaptureResultExtras resultExtras; // a dummy result (invalid)
2007 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002008 disconnect();
2009 }
2010}
2011
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012// ----------------------------------------------------------------------------
2013
Ruben Brunkcc776712015-02-17 20:18:47 -08002014// Provide client strong pointer for callbacks.
2015sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2016 String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2017 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2018 if (clientDescriptor != nullptr) {
2019 return sp<Client>{
2020 static_cast<Client*>(clientDescriptor->getValue().get())};
2021 }
2022 return sp<Client>{nullptr};
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023}
2024
Jianing Weicb0652e2014-03-12 18:29:36 -07002025void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2026 const CaptureResultExtras& resultExtras) {
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002027 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002028}
2029
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002030// NOTE: function is idempotent
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002031void CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002032 ALOGV("Client::disconnect");
Igor Murashkin634a5152013-02-20 17:15:11 -08002033 BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002034}
2035
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002036bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2037 return level == API_1;
2038}
2039
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002040CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2041 mClient(client) {
2042}
2043
2044void CameraService::Client::OpsCallback::opChanged(int32_t op,
2045 const String16& packageName) {
2046 sp<BasicClient> client = mClient.promote();
2047 if (client != NULL) {
2048 client->opChanged(op, packageName);
2049 }
2050}
2051
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002053// CameraState
2054// ----------------------------------------------------------------------------
2055
2056CameraService::CameraState::CameraState(const String8& id, int cost,
2057 const std::set<String8>& conflicting) : mId(id),
2058 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2059
2060CameraService::CameraState::~CameraState() {}
2061
2062ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2063 Mutex::Autolock lock(mStatusLock);
2064 return mStatus;
2065}
2066
2067CameraParameters CameraService::CameraState::getShimParams() const {
2068 return mShimParams;
2069}
2070
2071void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2072 mShimParams = params;
2073}
2074
2075int CameraService::CameraState::getCost() const {
2076 return mCost;
2077}
2078
2079std::set<String8> CameraService::CameraState::getConflicting() const {
2080 return mConflicting;
2081}
2082
2083String8 CameraService::CameraState::getId() const {
2084 return mId;
2085}
2086
2087// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002088// ClientEventListener
2089// ----------------------------------------------------------------------------
2090
2091void CameraService::ClientEventListener::onClientAdded(
2092 const resource_policy::ClientDescriptor<String8,
2093 sp<CameraService::BasicClient>>& descriptor) {
2094 auto basicClient = descriptor.getValue();
2095 if (basicClient.get() != nullptr) {
2096 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2097 notifier.noteStartCamera(descriptor.getKey(),
2098 static_cast<int>(basicClient->getClientUid()));
2099 }
2100}
2101
2102void CameraService::ClientEventListener::onClientRemoved(
2103 const resource_policy::ClientDescriptor<String8,
2104 sp<CameraService::BasicClient>>& descriptor) {
2105 auto basicClient = descriptor.getValue();
2106 if (basicClient.get() != nullptr) {
2107 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2108 notifier.noteStopCamera(descriptor.getKey(),
2109 static_cast<int>(basicClient->getClientUid()));
2110 }
2111}
2112
2113
2114// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002115// CameraClientManager
2116// ----------------------------------------------------------------------------
2117
Ruben Brunk99e69712015-05-26 17:25:07 -07002118CameraService::CameraClientManager::CameraClientManager() {
2119 setListener(std::make_shared<ClientEventListener>());
2120}
2121
Ruben Brunkcc776712015-02-17 20:18:47 -08002122CameraService::CameraClientManager::~CameraClientManager() {}
2123
2124sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2125 const String8& id) const {
2126 auto descriptor = get(id);
2127 if (descriptor == nullptr) {
2128 return sp<BasicClient>{nullptr};
2129 }
2130 return descriptor->getValue();
2131}
2132
2133String8 CameraService::CameraClientManager::toString() const {
2134 auto all = getAll();
2135 String8 ret("[");
2136 bool hasAny = false;
2137 for (auto& i : all) {
2138 hasAny = true;
2139 String8 key = i->getKey();
2140 int32_t cost = i->getCost();
2141 int32_t pid = i->getOwnerId();
2142 int32_t priority = i->getPriority();
2143 auto conflicting = i->getConflicting();
2144 auto clientSp = i->getValue();
2145 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002146 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002147 if (clientSp.get() != nullptr) {
2148 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002149 uid_t clientUid = clientSp->getClientUid();
2150 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002151 }
2152 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2153 PRId32 ", ", key.string(), cost, pid, priority);
2154
Ruben Brunk6267b532015-04-30 17:44:07 -07002155 if (clientSp.get() != nullptr) {
2156 ret.appendFormat("User Id: %d, ", clientUserId);
2157 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002158 if (packageName.size() != 0) {
2159 ret.appendFormat("Client Package Name: %s", packageName.string());
2160 }
2161
2162 ret.append(", Conflicting Client Devices: {");
2163 for (auto& j : conflicting) {
2164 ret.appendFormat("%s, ", j.string());
2165 }
2166 ret.append("})");
2167 }
2168 if (hasAny) ret.append("\n");
2169 ret.append("]\n");
2170 return ret;
2171}
2172
2173CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2174 const String8& key, const sp<BasicClient>& value, int32_t cost,
2175 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2176
2177 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2178 key, value, cost, conflictingKeys, priority, ownerId);
2179}
2180
2181CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2182 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2183 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2184 partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2185}
2186
2187// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188
2189static const int kDumpLockRetries = 50;
2190static const int kDumpLockSleep = 60000;
2191
2192static bool tryLock(Mutex& mutex)
2193{
2194 bool locked = false;
2195 for (int i = 0; i < kDumpLockRetries; ++i) {
2196 if (mutex.tryLock() == NO_ERROR) {
2197 locked = true;
2198 break;
2199 }
2200 usleep(kDumpLockSleep);
2201 }
2202 return locked;
2203}
2204
2205status_t CameraService::dump(int fd, const Vector<String16>& args) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002206 String8 result("Dump of the Camera Service:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002208 result.appendFormat("Permission Denial: "
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209 "can't dump CameraService from pid=%d, uid=%d\n",
2210 getCallingPid(),
2211 getCallingUid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212 write(fd, result.string(), result.size());
2213 } else {
2214 bool locked = tryLock(mServiceLock);
2215 // failed to lock - CameraService is probably deadlocked
2216 if (!locked) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002217 result.append("CameraService may be deadlocked\n");
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002218 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 }
2220
2221 bool hasClient = false;
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002222 if (!mModule) {
2223 result = String8::format("No camera module available!\n");
2224 write(fd, result.string(), result.size());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002225
2226 // Dump event log for error information
2227 dumpEventLog(fd);
2228
Kalle Lampila6ec3a152013-04-30 15:27:19 +03002229 if (locked) mServiceLock.unlock();
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002230 return NO_ERROR;
2231 }
2232
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002233 result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2234 result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2235 result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2236 result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
Ruben Brunkcc776712015-02-17 20:18:47 -08002237 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2238 String8 activeClientString = mActiveClientManager.toString();
2239 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
Ruben Brunk6267b532015-04-30 17:44:07 -07002240 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002241
Ruben Brunkf81648e2014-04-17 16:14:57 -07002242 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2243 if (desc == NULL) {
2244 result.appendFormat("Vendor tags left unimplemented.\n");
2245 } else {
2246 result.appendFormat("Vendor tag definitions:\n");
2247 }
2248
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002249 write(fd, result.string(), result.size());
Ruben Brunkf81648e2014-04-17 16:14:57 -07002250
2251 if (desc != NULL) {
2252 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2253 }
2254
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002255 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002256
2257 bool stateLocked = tryLock(mCameraStatesLock);
2258 if (!stateLocked) {
2259 result = String8::format("CameraStates in use, may be deadlocked\n");
2260 write(fd, result.string(), result.size());
2261 }
2262
2263 for (auto& state : mCameraStates) {
2264 String8 cameraId = state.first;
2265 result = String8::format("Camera %s information:\n", cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002266 camera_info info;
2267
Ruben Brunkcc776712015-02-17 20:18:47 -08002268 // TODO: Change getCameraInfo + HAL to use String cameraIds
2269 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002270 if (rc != OK) {
2271 result.appendFormat(" Error reading static information!\n");
2272 write(fd, result.string(), result.size());
2273 } else {
2274 result.appendFormat(" Facing: %s\n",
2275 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2276 result.appendFormat(" Orientation: %d\n", info.orientation);
2277 int deviceVersion;
Chien-Yu Chen676b21b2015-02-24 10:28:19 -08002278 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002279 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2280 } else {
2281 deviceVersion = info.device_version;
2282 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002283
2284 auto conflicting = state.second->getConflicting();
2285 result.appendFormat(" Resource Cost: %d\n", state.second->getCost());
2286 result.appendFormat(" Conflicting Devices:");
2287 for (auto& id : conflicting) {
2288 result.appendFormat(" %s", cameraId.string());
2289 }
2290 if (conflicting.size() == 0) {
2291 result.appendFormat(" NONE");
2292 }
2293 result.appendFormat("\n");
2294
2295 result.appendFormat(" Device version: %#x\n", deviceVersion);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002296 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2297 result.appendFormat(" Device static metadata:\n");
2298 write(fd, result.string(), result.size());
Eino-Ville Talvala428b77a2012-07-30 09:55:30 -07002299 dump_indented_camera_metadata(info.static_camera_characteristics,
Ruben Brunkf81648e2014-04-17 16:14:57 -07002300 fd, /*verbosity*/2, /*indentation*/4);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002301 } else {
2302 write(fd, result.string(), result.size());
2303 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002304
2305 CameraParameters p = state.second->getShimParams();
2306 if (!p.isEmpty()) {
2307 result = String8::format(" Camera1 API shim is using parameters:\n ");
2308 write(fd, result.string(), result.size());
2309 p.dump(fd, args);
2310 }
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002311 }
2312
Ruben Brunkcc776712015-02-17 20:18:47 -08002313 auto clientDescriptor = mActiveClientManager.get(cameraId);
2314 if (clientDescriptor == nullptr) {
2315 result = String8::format(" Device %s is closed, no client instance\n",
2316 cameraId.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002317 write(fd, result.string(), result.size());
2318 continue;
2319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 hasClient = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002321 result = String8::format(" Device %s is open. Client instance dump:\n\n",
2322 cameraId.string());
2323 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2324 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2325
2326 auto client = clientDescriptor->getValue();
2327 result.appendFormat("Client package: %s\n",
2328 String8(client->getPackageName()).string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002329 write(fd, result.string(), result.size());
Ruben Brunkcc776712015-02-17 20:18:47 -08002330
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -07002331 client->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002333
2334 if (stateLocked) mCameraStatesLock.unlock();
2335
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 if (!hasClient) {
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002337 result = String8::format("\nNo active camera clients yet.\n");
2338 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 }
2340
2341 if (locked) mServiceLock.unlock();
2342
Igor Murashkinff3e31d2013-10-23 16:40:06 -07002343 // Dump camera traces if there were any
2344 write(fd, "\n", 1);
2345 camera3::CameraTraces::dump(fd, args);
2346
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 // change logging level
2348 int n = args.size();
2349 for (int i = 0; i + 1 < n; i++) {
Eino-Ville Talvala611f6192012-05-31 12:28:23 -07002350 String16 verboseOption("-v");
2351 if (args[i] == verboseOption) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 String8 levelStr(args[i+1]);
2353 int level = atoi(levelStr.string());
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002354 result = String8::format("\nSetting log level to %d.\n", level);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 setLogLevel(level);
Eino-Ville Talvalaf5926132012-07-17 13:54:20 -07002356 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 }
2358 }
2359 }
2360 return NO_ERROR;
2361}
2362
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002363void CameraService::dumpEventLog(int fd) {
2364 String8 result = String8("\nPrior client events (most recent at top):\n");
2365
2366 Mutex::Autolock l(mLogLock);
2367 for (const auto& msg : mEventLog) {
2368 result.appendFormat(" %s\n", msg.string());
2369 }
2370
2371 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2372 result.append(" ...\n");
2373 } else if (mEventLog.size() == 0) {
2374 result.append(" [no events yet]\n");
2375 }
2376 result.append("\n");
2377
2378 write(fd, result.string(), result.size());
2379}
2380
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002381void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002382 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002383 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2384 if (mTorchClientMap[i] == who) {
2385 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002386 String8 cameraId = mTorchClientMap.keyAt(i);
2387 status_t res = mFlashlight->setTorchMode(cameraId, false);
2388 if (res) {
2389 ALOGE("%s: torch client died but couldn't turn off torch: "
2390 "%s (%d)", __FUNCTION__, strerror(-res), res);
2391 return;
2392 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002393 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002394 break;
2395 }
2396 }
2397}
2398
Ruben Brunkcc776712015-02-17 20:18:47 -08002399/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002400
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002401 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002402 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2403 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002404 */
2405
Ruben Brunka8ca9152015-04-07 14:23:40 -07002406 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2407
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002408 // check torch client
2409 handleTorchClientBinderDied(who);
2410
2411 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002412 if(!evictClientIdByRemote(who)) {
2413 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002414 return;
2415 }
2416
Ruben Brunkcc776712015-02-17 20:18:47 -08002417 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2418 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002419}
2420
Ruben Brunkcc776712015-02-17 20:18:47 -08002421void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2422 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002423}
2424
Ruben Brunkcc776712015-02-17 20:18:47 -08002425void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2426 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2427 // Do not lock mServiceLock here or can get into a deadlock from
2428 // connect() -> disconnect -> updateStatus
2429
2430 auto state = getCameraState(cameraId);
2431
2432 if (state == nullptr) {
2433 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2434 cameraId.string());
2435 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002436 }
2437
Ruben Brunkcc776712015-02-17 20:18:47 -08002438 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2439 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2440 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2441 (const String8& cameraId, ICameraServiceListener::Status status) {
2442
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002443 if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2444 // Update torch status if it has a flash unit.
2445 Mutex::Autolock al(mTorchStatusMutex);
2446 ICameraServiceListener::TorchStatus torchStatus;
2447 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2448 NAME_NOT_FOUND) {
2449 ICameraServiceListener::TorchStatus newTorchStatus =
2450 status == ICameraServiceListener::STATUS_PRESENT ?
2451 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2452 ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2453 if (torchStatus != newTorchStatus) {
2454 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2455 }
2456 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002457 }
2458
2459 Mutex::Autolock lock(mStatusListenerLock);
2460
2461 for (auto& listener : mListenerList) {
2462 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2463 int id = cameraIdToInt(cameraId);
2464 if (id != -1) listener->onStatusChanged(status, id);
2465 }
2466 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002467}
2468
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002469status_t CameraService::getTorchStatusLocked(
2470 const String8& cameraId,
2471 ICameraServiceListener::TorchStatus *status) const {
2472 if (!status) {
2473 return BAD_VALUE;
2474 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002475 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2476 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002477 // invalid camera ID or the camera doesn't have a flash unit
2478 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002479 }
2480
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002481 *status = mTorchStatusMap.valueAt(index);
2482 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002483}
2484
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002485status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002486 ICameraServiceListener::TorchStatus status) {
2487 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2488 if (index == NAME_NOT_FOUND) {
2489 return BAD_VALUE;
2490 }
2491 ICameraServiceListener::TorchStatus& item =
2492 mTorchStatusMap.editValueAt(index);
2493 item = status;
2494
2495 return OK;
2496}
2497
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498}; // namespace android