1 /*
2 * 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 */
16
17 #define LOG_TAG "CameraService"
18 //#define LOG_NDEBUG 0
19
20 #include <algorithm>
21 #include <climits>
22 #include <stdio.h>
23 #include <cstring>
24 #include <ctime>
25 #include <string>
26 #include <sys/types.h>
27 #include <inttypes.h>
28 #include <pthread.h>
29
30 #include <binder/AppOpsManager.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/IServiceManager.h>
33 #include <binder/MemoryBase.h>
34 #include <binder/MemoryHeapBase.h>
35 #include <binder/ProcessInfoService.h>
36 #include <camera/ICameraServiceProxy.h>
37 #include <cutils/atomic.h>
38 #include <cutils/properties.h>
39 #include <gui/Surface.h>
40 #include <hardware/hardware.h>
41 #include <media/AudioSystem.h>
42 #include <media/IMediaHTTPService.h>
43 #include <media/mediaplayer.h>
44 #include <mediautils/BatteryNotifier.h>
45 #include <utils/Errors.h>
46 #include <utils/Log.h>
47 #include <utils/String16.h>
48 #include <utils/Trace.h>
49 #include <system/camera_vendor_tags.h>
50 #include <system/camera_metadata.h>
51 #include <system/camera.h>
52
53 #include "CameraService.h"
54 #include "api1/CameraClient.h"
55 #include "api1/Camera2Client.h"
56 #include "api2/CameraDeviceClient.h"
57 #include "utils/CameraTraces.h"
58 #include "CameraDeviceFactory.h"
59
60 namespace android {
61
62 // ----------------------------------------------------------------------------
63 // Logging support -- this is for debugging only
64 // Use "adb shell dumpsys media.camera -v 1" to change it.
65 volatile int32_t gLogLevel = 0;
66
67 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
69
setLogLevel(int level)70 static void setLogLevel(int level) {
71 android_atomic_write(level, &gLogLevel);
72 }
73
74 // ----------------------------------------------------------------------------
75
76 extern "C" {
camera_device_status_change(const struct camera_module_callbacks * callbacks,int camera_id,int new_status)77 static 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*>(
82 static_cast<const CameraService*>(callbacks));
83
84 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
85 static_cast<camera_device_status_t>(new_status));
86 }
87
torch_mode_status_change(const struct camera_module_callbacks * callbacks,const char * camera_id,int new_status)88 static 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) {
101 case TORCH_MODE_STATUS_NOT_AVAILABLE:
102 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
103 break;
104 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;
109 break;
110 default:
111 ALOGE("Unknown torch status %d", new_status);
112 return;
113 }
114
115 cs->onTorchStatusChanged(
116 String8(camera_id),
117 status);
118 }
119 } // extern "C"
120
121 // ----------------------------------------------------------------------------
122
123 // This is ugly and only safe if we never re-create the CameraService, but
124 // should be ok for now.
125 static CameraService *gCameraService;
126
CameraService()127 CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH), mAllowedUsers(),
128 mSoundRef(0), mModule(0), mFlashlight(0) {
129 ALOGI("CameraService started (pid=%d)", getpid());
130 gCameraService = this;
131
132 this->camera_device_status_change = android::camera_device_status_change;
133 this->torch_mode_status_change = android::torch_mode_status_change;
134
135 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
136 }
137
onFirstRef()138 void CameraService::onFirstRef()
139 {
140 ALOGI("CameraService process starting");
141
142 BnCameraService::onFirstRef();
143
144 // Update battery life tracking if service is restarting
145 BatteryNotifier& notifier(BatteryNotifier::getInstance());
146 notifier.noteResetCamera();
147 notifier.noteResetFlashlight();
148
149 camera_module_t *rawModule;
150 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);
155 mNumberOfCameras = 0;
156 return;
157 }
158
159 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);
166
167 mNumberOfCameras = 0;
168 delete mModule;
169 mModule = nullptr;
170 return;
171 }
172
173 mNumberOfCameras = mModule->getNumberOfCameras();
174 mNumberOfNormalCameras = mNumberOfCameras;
175
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
183 int latestStrangeCameraId = INT_MAX;
184 for (int i = 0; i < mNumberOfCameras; i++) {
185 String8 cameraId = String8::format("%d", i);
186
187 // 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
208 // 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
214 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;
218 }
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);
249
250 CameraService::pingCameraServiceProxy();
251 }
252
pingCameraServiceProxy()253 void 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();
261 }
262
~CameraService()263 CameraService::~CameraService() {
264 if (mModule) {
265 delete mModule;
266 mModule = nullptr;
267 }
268 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
269 gCameraService = nullptr;
270 }
271
onDeviceStatusChanged(camera_device_status_t cameraId,camera_device_status_t newStatus)272 void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId,
273 camera_device_status_t newStatus) {
274 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
275 cameraId, newStatus);
276
277 String8 id = String8::format("%d", cameraId);
278 std::shared_ptr<CameraState> state = getCameraState(id);
279
280 if (state == nullptr) {
281 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
282 return;
283 }
284
285 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);
289 return;
290 }
291
292 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
293 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
294 newStatus));
295 sp<BasicClient> clientToDisconnect;
296 {
297 // Don't do this in updateStatus to avoid deadlock over mServiceLock
298 Mutex::Autolock lock(mServiceLock);
299
300 // 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);
303
304 // Remove cached shim parameters
305 state->setShimParams(CameraParameters());
306
307 // 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{});
313 }
314
315 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
316 __FUNCTION__, id.string());
317
318 // 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();
324 }
325
326 } else {
327 if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
328 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
329 newStatus));
330 }
331 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
332 }
333
334 }
335
onTorchStatusChanged(const String8 & cameraId,ICameraServiceListener::TorchStatus newStatus)336 void CameraService::onTorchStatusChanged(const String8& cameraId,
337 ICameraServiceListener::TorchStatus newStatus) {
338 Mutex::Autolock al(mTorchStatusMutex);
339 onTorchStatusChangedLocked(cameraId, newStatus);
340 }
341
onTorchStatusChangedLocked(const String8 & cameraId,ICameraServiceListener::TorchStatus newStatus)342 void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
343 ICameraServiceListener::TorchStatus newStatus) {
344 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
345 __FUNCTION__, cameraId.string(), newStatus);
346
347 ICameraServiceListener::TorchStatus status;
348 status_t res = getTorchStatusLocked(cameraId, &status);
349 if (res) {
350 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
351 __FUNCTION__, cameraId.string(), strerror(-res), res);
352 return;
353 }
354 if (status == newStatus) {
355 return;
356 }
357
358 res = setTorchStatusLocked(cameraId, newStatus);
359 if (res) {
360 ALOGE("%s: Failed to set the torch status", __FUNCTION__, (uint32_t)newStatus);
361 return;
362 }
363
364 {
365 // Update battery life logging for flashlight
366 Mutex::Autolock al(mTorchUidMapMutex);
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 {
393 Mutex::Autolock lock(mStatusListenerLock);
394 for (auto& i : mListenerList) {
395 i->onTorchStatusChanged(newStatus, String16{cameraId});
396 }
397 }
398 }
399
getNumberOfCameras()400 int32_t CameraService::getNumberOfCameras() {
401 return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
402 }
403
getNumberOfCameras(int type)404 int32_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 }
415 }
416
getCameraInfo(int cameraId,struct CameraInfo * cameraInfo)417 status_t CameraService::getCameraInfo(int cameraId,
418 struct CameraInfo* cameraInfo) {
419 if (!mModule) {
420 return -ENODEV;
421 }
422
423 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
424 return BAD_VALUE;
425 }
426
427 struct camera_info info;
428 status_t rc = filterGetInfoErrorCode(
429 mModule->getCameraInfo(cameraId, &info));
430 cameraInfo->facing = info.facing;
431 cameraInfo->orientation = info.orientation;
432 return rc;
433 }
434
cameraIdToInt(const String8 & cameraId)435 int 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 }
444
generateShimMetadata(int cameraId,CameraMetadata * cameraInfo)445 status_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
464 CameraParameters shimParams;
465 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
466 // Error logged by callee
467 return ret;
468 }
469
470 Vector<Size> sizes;
471 Vector<Size> jpegSizes;
472 Vector<int32_t> formats;
473 const char* supportedPreviewFormats;
474 {
475 shimParams.getSupportedPreviewSizes(/*out*/sizes);
476 shimParams.getSupportedPreviewFormats(/*out*/formats);
477 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
478 }
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
486 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
487
488 Vector<int32_t> streamConfigs;
489 streamConfigs.setCapacity(streamConfigSize);
490
491 for (size_t i = 0; i < formats.size(); ++i) {
492 for (size_t j = 0; j < sizes.size(); ++j) {
493 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);
497 }
498 }
499
500 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
507 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
508 streamConfigs.array(), streamConfigSize)) != OK) {
509 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
getCameraCharacteristics(int cameraId,CameraMetadata * cameraInfo)530 status_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
542 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
543 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
544 return BAD_VALUE;
545 }
546
547 int facing;
548 status_t ret = OK;
549 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
550 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__);
560
561 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
562 return ret;
563 }
564
565 } else {
566 /**
567 * Normal HAL 2.1+ codepath.
568 */
569 struct camera_info info;
570 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
571 *cameraInfo = info.static_camera_characteristics;
572 }
573
574 return ret;
575 }
576
getCallingPid()577 int CameraService::getCallingPid() {
578 return IPCThreadState::self()->getCallingPid();
579 }
580
getCallingUid()581 int CameraService::getCallingUid() {
582 return IPCThreadState::self()->getCallingUid();
583 }
584
getFormattedCurrentTime()585 String8 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
getCameraPriorityFromProcState(int procState)592 int CameraService::getCameraPriorityFromProcState(int procState) {
593 // Find the priority for the camera usage based on the process state. Higher priority clients
594 // win for evictions.
595 if (procState < 0) {
596 ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
597 procState);
598 return -1;
599 }
600 return INT_MAX - procState;
601 }
602
getCameraVendorTagDescriptor(sp<VendorTagDescriptor> & desc)603 status_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
609 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
610 return OK;
611 }
612
getDeviceVersion(int cameraId,int * facing)613 int CameraService::getDeviceVersion(int cameraId, int* facing) {
614 struct camera_info info;
615 if (mModule->getCameraInfo(cameraId, &info) != OK) {
616 return -1;
617 }
618
619 int deviceVersion;
620 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
621 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
filterGetInfoErrorCode(status_t err)633 status_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;
642 }
643
setUpVendorTags()644 bool CameraService::setUpVendorTags() {
645 vendor_tag_ops_t vOps = vendor_tag_ops_t();
646
647 // Check if vendor operations have been implemented
648 if (!mModule->isVendorTagDefined()) {
649 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
650 return false;
651 }
652
653 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
654 mModule->getVendorTagOps(&vOps);
655 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
makeClient(const sp<CameraService> & cameraService,const sp<IInterface> & cameraCb,const String16 & packageName,const String8 & cameraId,int facing,int clientPid,uid_t clientUid,int servicePid,bool legacyMode,int halVersion,int deviceVersion,apiLevel effectiveApiLevel,sp<BasicClient> * client)682 status_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;
694 }
695
696 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
toString(std::set<userid_t> intSet)752 String8 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
initializeShimMetadata(int cameraId)766 status_t CameraService::initializeShimMetadata(int cameraId) {
767 int uid = getCallingUid();
768
769 String16 internalPackageName("media");
770 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;
778 }
779 return NO_ERROR;
780 }
781
getLegacyParametersLazy(int cameraId,CameraParameters * parameters)782 status_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
795 String8 id = String8::format("%d", cameraId);
796
797 // Check if we already have parameters
798 {
799 // Scope for service lock
800 Mutex::Autolock lock(mServiceLock);
801 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;
810 }
811 }
812
813 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;
829 }
830 CameraParameters p = cameraState->getShimParams();
831 if (!p.isEmpty()) {
832 *parameters = p;
833 return NO_ERROR;
834 }
835 }
836
837 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
838 __FUNCTION__);
839 return INVALID_OPERATION;
840 }
841
validateConnectLocked(const String8 & cameraId,int & clientUid) const842 status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid)
843 const {
844
845 int callingPid = getCallingPid();
846
847 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()) {
852 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
853 callingPid, clientUid);
854 return PERMISSION_DENIED;
855 }
856 }
857
858 if (!mModule) {
859 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
860 callingPid);
861 return -ENODEV;
862 }
863
864 if (getCameraState(cameraId) == nullptr) {
865 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
866 cameraId.string());
867 return -ENODEV;
868 }
869
870 // Check device policy for this camera
871 char value[PROPERTY_VALUE_MAX];
872 char key[PROPERTY_KEY_MAX];
873 userid_t clientUserId = multiuser_get_user_id(clientUid);
874 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
875 property_get(key, value, "0");
876 if (strcmp(value, "1") == 0) {
877 // Camera is disabled by DevicePolicyManager.
878 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
879 "policy)", callingPid, cameraId.string());
880 return -EACCES;
881 }
882
883 // Only allow clients who are being used by the current foreground device user, unless calling
884 // from our own process.
885 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());
889 return PERMISSION_DENIED;
890 }
891
892 return checkIfDeviceIsUsable(cameraId);
893 }
894
checkIfDeviceIsUsable(const String8 & cameraId) const895 status_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();
905 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
906 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
907 callingPid, cameraId.string());
908 return -ENODEV;
909 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
910 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
911 callingPid, cameraId.string());
912 return -EBUSY;
913 }
914
915 return NO_ERROR;
916 }
917
finishConnectLocked(const sp<BasicClient> & client,const CameraService::DescriptorPtr & desc)918 void CameraService::finishConnectLocked(const sp<BasicClient>& client,
919 const CameraService::DescriptorPtr& desc) {
920
921 // 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
handleEvictionsLocked(const String8 & cameraId,int clientPid,apiLevel effectiveApiLevel,const sp<IBinder> & remoteCallback,const String8 & packageName,sp<BasicClient> * client,std::shared_ptr<resource_policy::ClientDescriptor<String8,sp<BasicClient>>> * partial)940 status_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;
947 std::vector<DescriptorPtr> evictedClients;
948 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
958 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) {
962 ALOGI("CameraService::connect X (PID %d) (second call from same"
963 " app binder, returning the same client)", clientPid);
964 *client = clientSp;
965 return NO_ERROR;
966 }
967 }
968 }
969 }
970
971 // 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 }
975
976 // Get current active client PIDs
977 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
978 ownerPids.push_back(clientPid);
979
980 // 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);
985
986 // Get priorites of all active PIDs
987 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
988 /*out*/&priorities[0]);
989
990 // 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);
996
997 // 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());
1002 return BAD_VALUE;
1003 }
1004
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 "
1026 "(PID %d, priority %d) due to eviction policy", curTime.string(),
1027 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());
1035 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());
1039 }
1040
1041 // Log the client's attempt
1042 Mutex::Autolock l(mLogLock);
1043 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());
1062 evictedClients.push_back(i);
1063
1064 // Log the clients evicted
1065 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 ")",
1068 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());
1076 }
1077 }
1078
1079 // 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
1089 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1090 }
1091
1092 IPCThreadState::self()->restoreCallingIdentity(token);
1093
1094 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
1114 // 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;
1120 }
1121
1122 *partial = clientDescriptor;
1123 return NO_ERROR;
1124 }
1125
connect(const sp<ICameraClient> & cameraClient,int cameraId,const String16 & clientPackageName,int clientUid,sp<ICamera> & device)1126 status_t CameraService::connect(
1127 const sp<ICameraClient>& cameraClient,
1128 int cameraId,
1129 const String16& clientPackageName,
1130 int clientUid,
1131 /*out*/
1132 sp<ICamera>& device) {
1133
1134 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,
1138 clientPackageName, clientUid, API_1, false, false, /*out*/client);
1139
1140 if(ret != NO_ERROR) {
1141 logRejected(id, getCallingPid(), String8(clientPackageName),
1142 String8::format("%s (%d)", strerror(-ret), ret));
1143 return ret;
1144 }
1145
1146 device = client;
1147 return NO_ERROR;
1148 }
1149
connectLegacy(const sp<ICameraClient> & cameraClient,int cameraId,int halVersion,const String16 & clientPackageName,int clientUid,sp<ICamera> & device)1150 status_t CameraService::connectLegacy(
1151 const sp<ICameraClient>& cameraClient,
1152 int cameraId, int halVersion,
1153 const String16& clientPackageName,
1154 int clientUid,
1155 /*out*/
1156 sp<ICamera>& device) {
1157
1158 String8 id = String8::format("%d", cameraId);
1159 int apiVersion = mModule->getModuleApiVersion();
1160 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
1161 apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
1162 /*
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 */
1168 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
1169 __FUNCTION__, apiVersion);
1170 logRejected(id, getCallingPid(), String8(clientPackageName),
1171 String8("HAL module version doesn't support legacy HAL connections"));
1172 return INVALID_OPERATION;
1173 }
1174
1175 status_t ret = NO_ERROR;
1176 sp<Client> client = nullptr;
1177 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
1178 clientUid, API_1, true, false, /*out*/client);
1179
1180 if(ret != NO_ERROR) {
1181 logRejected(id, getCallingPid(), String8(clientPackageName),
1182 String8::format("%s (%d)", strerror(-ret), ret));
1183 return ret;
1184 }
1185
1186 device = client;
1187 return NO_ERROR;
1188 }
1189
connectDevice(const sp<ICameraDeviceCallbacks> & cameraCb,int cameraId,const String16 & clientPackageName,int clientUid,sp<ICameraDeviceUser> & device)1190 status_t CameraService::connectDevice(
1191 const sp<ICameraDeviceCallbacks>& cameraCb,
1192 int cameraId,
1193 const String16& clientPackageName,
1194 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,
1202 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
1203 /*out*/client);
1204
1205 if(ret != NO_ERROR) {
1206 logRejected(id, getCallingPid(), String8(clientPackageName),
1207 String8::format("%s (%d)", strerror(-ret), ret));
1208 return ret;
1209 }
1210
1211 device = client;
1212 return NO_ERROR;
1213 }
1214
setTorchMode(const String16 & cameraId,bool enabled,const sp<IBinder> & clientBinder)1215 status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1216 const sp<IBinder>& clientBinder) {
1217 if (enabled && clientBinder == nullptr) {
1218 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1219 return -EINVAL;
1220 }
1221
1222 String8 id = String8(cameraId.string());
1223 int uid = getCallingUid();
1224
1225 // verify id is valid.
1226 auto state = getCameraState(id);
1227 if (state == nullptr) {
1228 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1229 return -EINVAL;
1230 }
1231
1232 ICameraServiceListener::Status cameraStatus = state->getStatus();
1233 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1234 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1235 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1236 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) {
1250 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1251 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
1262 {
1263 // Update UID map - this is used in the torch status changed callbacks, so must be done
1264 // before setTorchMode
1265 Mutex::Autolock al(mTorchUidMapMutex);
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
1275 status_t res = mFlashlight->setTorchMode(id, enabled);
1276
1277 if (res) {
1278 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1279 __FUNCTION__, id.string(), enabled, strerror(-res), res);
1280 return res;
1281 }
1282
1283 {
1284 // update the link to client's death
1285 Mutex::Autolock al(mTorchClientMapMutex);
1286 ssize_t index = mTorchClientMap.indexOfKey(id);
1287 BatteryNotifier& notifier(BatteryNotifier::getInstance());
1288 if (enabled) {
1289 if (index == NAME_NOT_FOUND) {
1290 mTorchClientMap.add(id, clientBinder);
1291 } else {
1292 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1293 mTorchClientMap.replaceValueAt(index, clientBinder);
1294 }
1295 clientBinder->linkToDeath(this);
1296 } else if (index != NAME_NOT_FOUND) {
1297 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1298 }
1299 }
1300
1301 return OK;
1302 }
1303
notifySystemEvent(int32_t eventId,const int32_t * args,size_t length)1304 void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
1305 switch(eventId) {
1306 case ICameraService::USER_SWITCHED: {
1307 doUserSwitch(/*newUserIds*/args, /*length*/length);
1308 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
addListener(const sp<ICameraServiceListener> & listener)1319 status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
1320 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1321
1322 if (listener == nullptr) {
1323 ALOGE("%s: Listener must not be null", __FUNCTION__);
1324 return BAD_VALUE;
1325 }
1326
1327 Mutex::Autolock lock(mServiceLock);
1328
1329 {
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 }
1337 }
1338
1339 mListenerList.push_back(listener);
1340 }
1341
1342
1343 /* Immediately signal current status to this listener only */
1344 {
1345 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);
1352 }
1353 }
1354
1355 /* 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++ ) {
1359 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1360 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
1361 }
1362 }
1363
1364 return OK;
1365 }
1366
removeListener(const sp<ICameraServiceListener> & listener)1367 status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
1368 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1369
1370 if (listener == 0) {
1371 ALOGE("%s: Listener must not be null", __FUNCTION__);
1372 return BAD_VALUE;
1373 }
1374
1375 Mutex::Autolock lock(mServiceLock);
1376
1377 {
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 }
1384 }
1385 }
1386
1387 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1388 __FUNCTION__, listener.get());
1389
1390 return BAD_VALUE;
1391 }
1392
getLegacyParameters(int cameraId,String16 * parameters)1393 status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
1394 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
supportsCameraApi(int cameraId,int apiVersion)1417 status_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:
1448 case CAMERA_DEVICE_API_VERSION_3_3:
1449 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
removeByClient(const BasicClient * client)1463 void CameraService::removeByClient(const BasicClient* client) {
1464 Mutex::Autolock lock(mServiceLock);
1465 for (auto& i : mActiveClientManager.getAll()) {
1466 auto clientSp = i->getValue();
1467 if (clientSp.get() == client) {
1468 mActiveClientManager.remove(i);
1469 }
1470 }
1471 }
1472
evictClientIdByRemote(const wp<IBinder> & remote)1473 bool 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);
1481
1482
1483 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);
1495
1496 // Notify the client of disconnection
1497 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1498 CaptureResultExtras());
1499 }
1500 }
1501
1502 // 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
1506 // Do not clear caller identity, remote caller should be client proccess
1507
1508 for (auto& i : evicted) {
1509 if (i.get() != nullptr) {
1510 i->disconnect();
1511 ret = true;
1512 }
1513 }
1514
1515 // Reacquire mServiceLock
1516 mServiceLock.lock();
1517
1518 } // lock is destroyed, allow further connect calls
1519
1520 return ret;
1521 }
1522
1523
1524 /**
1525 * Check camera capabilities, such as support for basic color operation
1526 */
checkCameraCapabilities(int id,camera_info info,int * latestStrangeCameraId)1527 int 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
getCameraState(const String8 & cameraId) const1571 std::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;
1579 }
1580 }
1581 return state;
1582 }
1583
removeClientLocked(const String8 & cameraId)1584 sp<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();
1594 }
1595
doUserSwitch(const int32_t * newUserId,size_t length)1596 void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
1597 // Acquire mServiceLock and prevent other clients from connecting
1598 std::unique_ptr<AutoConditionLock> lock =
1599 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1600
1601 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]));
1609 }
1610
1611
1612 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);
1620
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
1631 // 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
1638 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());
1644
1645 // Log the clients evicted
1646 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
1647 PRId32 ", priority %" PRId32 ")\n - Evicted due to user switch.",
1648 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1649 i->getOwnerId(), i->getPriority()));
1650
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 }
1669
logEvent(const char * event)1670 void CameraService::logEvent(const char* event) {
1671 String8 curTime = getFormattedCurrentTime();
1672 Mutex::Autolock l(mLogLock);
1673 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
1674 }
1675
logDisconnected(const char * cameraId,int clientPid,const char * clientPackage)1676 void CameraService::logDisconnected(const char* cameraId, int clientPid,
1677 const char* clientPackage) {
1678 // Log the clients evicted
1679 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1680 clientPackage, clientPid));
1681 }
1682
logConnected(const char * cameraId,int clientPid,const char * clientPackage)1683 void CameraService::logConnected(const char* cameraId, int clientPid,
1684 const char* clientPackage) {
1685 // Log the clients evicted
1686 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1687 clientPackage, clientPid));
1688 }
1689
logRejected(const char * cameraId,int clientPid,const char * clientPackage,const char * reason)1690 void CameraService::logRejected(const char* cameraId, int clientPid,
1691 const char* clientPackage, const char* reason) {
1692 // Log the client rejected
1693 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1694 cameraId, clientPackage, clientPid, reason));
1695 }
1696
logUserSwitch(const std::set<userid_t> & oldUserIds,const std::set<userid_t> & newUserIds)1697 void 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);
1701 // Log the new and old users
1702 logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1703 oldUsers.string(), newUsers.string()));
1704 }
1705
logDeviceRemoved(const char * cameraId,const char * reason)1706 void 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
logDeviceAdded(const char * cameraId,const char * reason)1711 void 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
logClientDied(int clientPid,const char * reason)1716 void 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));
1719 }
1720
logServiceError(const char * msg,int errorCode)1721 void 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
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1726 status_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
1732 // Permission checks
1733 switch (code) {
1734 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 }
1749 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 }
1763 }
1764
1765 return BnCameraService::onTransact(code, data, reply, flags);
1766 }
1767
1768 // 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
newMediaPlayer(const char * file)1772 MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1773 MediaPlayer* mp = new MediaPlayer();
1774 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1775 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1776 mp->prepare();
1777 } else {
1778 ALOGE("Failed to load CameraService sounds: %s", file);
1779 return NULL;
1780 }
1781 return mp;
1782 }
1783
loadSound()1784 void 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
releaseSound()1793 void 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
playSound(sound_kind kind)1806 void 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) {
1811 player->seekTo(0);
1812 player->start();
1813 }
1814 }
1815
1816 // ----------------------------------------------------------------------------
1817
Client(const sp<CameraService> & cameraService,const sp<ICameraClient> & cameraClient,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)1818 CameraService::Client::Client(const sp<CameraService>& cameraService,
1819 const sp<ICameraClient>& cameraClient,
1820 const String16& clientPackageName,
1821 int cameraId, int cameraFacing,
1822 int clientPid, uid_t clientUid,
1823 int servicePid) :
1824 CameraService::BasicClient(cameraService,
1825 IInterface::asBinder(cameraClient),
1826 clientPackageName,
1827 cameraId, cameraFacing,
1828 clientPid, clientUid,
1829 servicePid)
1830 {
1831 int callingPid = getCallingPid();
1832 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
1833
1834 mRemoteCallback = cameraClient;
1835
1836 cameraService->loadSound();
1837
1838 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
1839 }
1840
1841 // tear down the client
~Client()1842 CameraService::Client::~Client() {
1843 ALOGV("~Client");
1844 mDestructionStarted = true;
1845
1846 mCameraService->releaseSound();
1847 // unconditionally disconnect. function is idempotent
1848 Client::disconnect();
1849 }
1850
BasicClient(const sp<CameraService> & cameraService,const sp<IBinder> & remoteCallback,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)1851 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
1852 const sp<IBinder>& remoteCallback,
1853 const String16& clientPackageName,
1854 int cameraId, int cameraFacing,
1855 int clientPid, uid_t clientUid,
1856 int servicePid):
1857 mClientPackageName(clientPackageName), mDisconnected(false)
1858 {
1859 mCameraService = cameraService;
1860 mRemoteBinder = remoteCallback;
1861 mCameraId = cameraId;
1862 mCameraFacing = cameraFacing;
1863 mClientPid = clientPid;
1864 mClientUid = clientUid;
1865 mServicePid = servicePid;
1866 mOpsActive = false;
1867 mDestructionStarted = false;
1868 }
1869
~BasicClient()1870 CameraService::BasicClient::~BasicClient() {
1871 ALOGV("~BasicClient");
1872 mDestructionStarted = true;
1873 }
1874
disconnect()1875 void CameraService::BasicClient::disconnect() {
1876 if (mDisconnected) {
1877 ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1878 mCameraId);
1879 return;
1880 }
1881 mDisconnected = true;;
1882
1883 mCameraService->removeByClient(this);
1884 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
1885 String8(mClientPackageName));
1886
1887 sp<IBinder> remote = getRemote();
1888 if (remote != nullptr) {
1889 remote->unlinkToDeath(mCameraService);
1890 }
1891
1892 finishCameraOps();
1893 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1894
1895 // client shouldn't be able to call into us anymore
1896 mClientPid = 0;
1897 }
1898
getPackageName() const1899 String16 CameraService::BasicClient::getPackageName() const {
1900 return mClientPackageName;
1901 }
1902
1903
getClientPid() const1904 int CameraService::BasicClient::getClientPid() const {
1905 return mClientPid;
1906 }
1907
getClientUid() const1908 uid_t CameraService::BasicClient::getClientUid() const {
1909 return mClientUid;
1910 }
1911
canCastToApiClient(apiLevel level) const1912 bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1913 // Defaults to API2.
1914 return level == API_2;
1915 }
1916
startCameraOps()1917 status_t CameraService::BasicClient::startCameraOps() {
1918 int32_t res;
1919 // Notify app ops that the camera is not available
1920 mOpsCallback = new OpsCallback(this);
1921
1922 {
1923 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1924 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1925 }
1926
1927 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1928 mClientPackageName, mOpsCallback);
1929 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1930 mClientUid, mClientPackageName);
1931
1932 if (res == AppOpsManager::MODE_ERRORED) {
1933 ALOGI("Camera %d: Access for \"%s\" has been revoked",
1934 mCameraId, String8(mClientPackageName).string());
1935 return PERMISSION_DENIED;
1936 }
1937
1938 if (res == AppOpsManager::MODE_IGNORED) {
1939 ALOGI("Camera %d: Access for \"%s\" has been restricted",
1940 mCameraId, String8(mClientPackageName).string());
1941 // Return the same error as for device policy manager rejection
1942 return -EACCES;
1943 }
1944
1945 mOpsActive = true;
1946
1947 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1948 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
1949 String8::format("%d", mCameraId));
1950
1951 return OK;
1952 }
1953
finishCameraOps()1954 status_t CameraService::BasicClient::finishCameraOps() {
1955 // Check if startCameraOps succeeded, and if so, finish the camera op
1956 if (mOpsActive) {
1957 // Notify app ops that the camera is available again
1958 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1959 mClientPackageName);
1960 mOpsActive = false;
1961
1962 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1963 ICameraServiceListener::STATUS_ENUMERATING};
1964
1965 // Transition to PRESENT if the camera is not in either of the rejected states
1966 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
1967 String8::format("%d", mCameraId), rejected);
1968
1969 // Notify flashlight that a camera device is closed.
1970 mCameraService->mFlashlight->deviceClosed(
1971 String8::format("%d", mCameraId));
1972 }
1973 // Always stop watching, even if no camera op is active
1974 if (mOpsCallback != NULL) {
1975 mAppOpsManager.stopWatchingMode(mOpsCallback);
1976 }
1977 mOpsCallback.clear();
1978
1979 return OK;
1980 }
1981
opChanged(int32_t op,const String16 & packageName)1982 void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1983 String8 name(packageName);
1984 String8 myName(mClientPackageName);
1985
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,
1993 mClientUid, mClientPackageName);
1994 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();
2006 CaptureResultExtras resultExtras; // a dummy result (invalid)
2007 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
2008 disconnect();
2009 }
2010 }
2011
2012 // ----------------------------------------------------------------------------
2013
2014 // Provide client strong pointer for callbacks.
getClientFromCookie(void * user)2015 sp<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};
2023 }
2024
notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,const CaptureResultExtras & resultExtras)2025 void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2026 const CaptureResultExtras& resultExtras) {
2027 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2028 }
2029
2030 // NOTE: function is idempotent
disconnect()2031 void CameraService::Client::disconnect() {
2032 ALOGV("Client::disconnect");
2033 BasicClient::disconnect();
2034 }
2035
canCastToApiClient(apiLevel level) const2036 bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2037 return level == API_1;
2038 }
2039
OpsCallback(wp<BasicClient> client)2040 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2041 mClient(client) {
2042 }
2043
opChanged(int32_t op,const String16 & packageName)2044 void 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
2052 // ----------------------------------------------------------------------------
2053 // CameraState
2054 // ----------------------------------------------------------------------------
2055
CameraState(const String8 & id,int cost,const std::set<String8> & conflicting)2056 CameraService::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
~CameraState()2060 CameraService::CameraState::~CameraState() {}
2061
getStatus() const2062 ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2063 Mutex::Autolock lock(mStatusLock);
2064 return mStatus;
2065 }
2066
getShimParams() const2067 CameraParameters CameraService::CameraState::getShimParams() const {
2068 return mShimParams;
2069 }
2070
setShimParams(const CameraParameters & params)2071 void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2072 mShimParams = params;
2073 }
2074
getCost() const2075 int CameraService::CameraState::getCost() const {
2076 return mCost;
2077 }
2078
getConflicting() const2079 std::set<String8> CameraService::CameraState::getConflicting() const {
2080 return mConflicting;
2081 }
2082
getId() const2083 String8 CameraService::CameraState::getId() const {
2084 return mId;
2085 }
2086
2087 // ----------------------------------------------------------------------------
2088 // ClientEventListener
2089 // ----------------------------------------------------------------------------
2090
onClientAdded(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2091 void 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
onClientRemoved(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2102 void 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 // ----------------------------------------------------------------------------
2115 // CameraClientManager
2116 // ----------------------------------------------------------------------------
2117
CameraClientManager()2118 CameraService::CameraClientManager::CameraClientManager() {
2119 setListener(std::make_shared<ClientEventListener>());
2120 }
2121
~CameraClientManager()2122 CameraService::CameraClientManager::~CameraClientManager() {}
2123
getCameraClient(const String8 & id) const2124 sp<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
toString() const2133 String8 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;
2146 userid_t clientUserId = 0;
2147 if (clientSp.get() != nullptr) {
2148 packageName = String8{clientSp->getPackageName()};
2149 uid_t clientUid = clientSp->getClientUid();
2150 clientUserId = multiuser_get_user_id(clientUid);
2151 }
2152 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2153 PRId32 ", ", key.string(), cost, pid, priority);
2154
2155 if (clientSp.get() != nullptr) {
2156 ret.appendFormat("User Id: %d, ", clientUserId);
2157 }
2158 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
makeClientDescriptor(const String8 & key,const sp<BasicClient> & value,int32_t cost,const std::set<String8> & conflictingKeys,int32_t priority,int32_t ownerId)2173 CameraService::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
makeClientDescriptor(const sp<BasicClient> & value,const CameraService::DescriptorPtr & partial)2181 CameraService::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 // ----------------------------------------------------------------------------
2188
2189 static const int kDumpLockRetries = 50;
2190 static const int kDumpLockSleep = 60000;
2191
tryLock(Mutex & mutex)2192 static 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
dump(int fd,const Vector<String16> & args)2205 status_t CameraService::dump(int fd, const Vector<String16>& args) {
2206 String8 result("Dump of the Camera Service:\n");
2207 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
2208 result.appendFormat("Permission Denial: "
2209 "can't dump CameraService from pid=%d, uid=%d\n",
2210 getCallingPid(),
2211 getCallingUid());
2212 write(fd, result.string(), result.size());
2213 } else {
2214 bool locked = tryLock(mServiceLock);
2215 // failed to lock - CameraService is probably deadlocked
2216 if (!locked) {
2217 result.append("CameraService may be deadlocked\n");
2218 write(fd, result.string(), result.size());
2219 }
2220
2221 bool hasClient = false;
2222 if (!mModule) {
2223 result = String8::format("No camera module available!\n");
2224 write(fd, result.string(), result.size());
2225
2226 // Dump event log for error information
2227 dumpEventLog(fd);
2228
2229 if (locked) mServiceLock.unlock();
2230 return NO_ERROR;
2231 }
2232
2233 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());
2237 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2238 String8 activeClientString = mActiveClientManager.toString();
2239 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2240 result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
2241
2242 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
2249 write(fd, result.string(), result.size());
2250
2251 if (desc != NULL) {
2252 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2253 }
2254
2255 dumpEventLog(fd);
2256
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());
2266 camera_info info;
2267
2268 // TODO: Change getCameraInfo + HAL to use String cameraIds
2269 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
2270 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;
2278 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
2279 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2280 } else {
2281 deviceVersion = info.device_version;
2282 }
2283
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);
2296 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2297 result.appendFormat(" Device static metadata:\n");
2298 write(fd, result.string(), result.size());
2299 dump_indented_camera_metadata(info.static_camera_characteristics,
2300 fd, /*verbosity*/2, /*indentation*/4);
2301 } else {
2302 write(fd, result.string(), result.size());
2303 }
2304
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 }
2311 }
2312
2313 auto clientDescriptor = mActiveClientManager.get(cameraId);
2314 if (clientDescriptor == nullptr) {
2315 result = String8::format(" Device %s is closed, no client instance\n",
2316 cameraId.string());
2317 write(fd, result.string(), result.size());
2318 continue;
2319 }
2320 hasClient = true;
2321 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());
2329 write(fd, result.string(), result.size());
2330
2331 client->dump(fd, args);
2332 }
2333
2334 if (stateLocked) mCameraStatesLock.unlock();
2335
2336 if (!hasClient) {
2337 result = String8::format("\nNo active camera clients yet.\n");
2338 write(fd, result.string(), result.size());
2339 }
2340
2341 if (locked) mServiceLock.unlock();
2342
2343 // Dump camera traces if there were any
2344 write(fd, "\n", 1);
2345 camera3::CameraTraces::dump(fd, args);
2346
2347 // change logging level
2348 int n = args.size();
2349 for (int i = 0; i + 1 < n; i++) {
2350 String16 verboseOption("-v");
2351 if (args[i] == verboseOption) {
2352 String8 levelStr(args[i+1]);
2353 int level = atoi(levelStr.string());
2354 result = String8::format("\nSetting log level to %d.\n", level);
2355 setLogLevel(level);
2356 write(fd, result.string(), result.size());
2357 }
2358 }
2359 }
2360 return NO_ERROR;
2361 }
2362
dumpEventLog(int fd)2363 void 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
handleTorchClientBinderDied(const wp<IBinder> & who)2381 void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
2382 Mutex::Autolock al(mTorchClientMapMutex);
2383 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
2386 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 }
2393 mTorchClientMap.removeItemsAt(i);
2394 break;
2395 }
2396 }
2397 }
2398
binderDied(const wp<IBinder> & who)2399 /*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
2400
2401 /**
2402 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2403 * binder driver
2404 */
2405
2406 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2407
2408 // check torch client
2409 handleTorchClientBinderDied(who);
2410
2411 // check camera device client
2412 if(!evictClientIdByRemote(who)) {
2413 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
2414 return;
2415 }
2416
2417 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2418 __FUNCTION__);
2419 }
2420
updateStatus(ICameraServiceListener::Status status,const String8 & cameraId)2421 void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2422 updateStatus(status, cameraId, {});
2423 }
2424
updateStatus(ICameraServiceListener::Status status,const String8 & cameraId,std::initializer_list<ICameraServiceListener::Status> rejectSourceStates)2425 void 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;
2436 }
2437
2438 // 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
2443 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 }
2457 }
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 });
2467 }
2468
getTorchStatusLocked(const String8 & cameraId,ICameraServiceListener::TorchStatus * status) const2469 status_t CameraService::getTorchStatusLocked(
2470 const String8& cameraId,
2471 ICameraServiceListener::TorchStatus *status) const {
2472 if (!status) {
2473 return BAD_VALUE;
2474 }
2475 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2476 if (index == NAME_NOT_FOUND) {
2477 // invalid camera ID or the camera doesn't have a flash unit
2478 return NAME_NOT_FOUND;
2479 }
2480
2481 *status = mTorchStatusMap.valueAt(index);
2482 return OK;
2483 }
2484
setTorchStatusLocked(const String8 & cameraId,ICameraServiceListener::TorchStatus status)2485 status_t CameraService::setTorchStatusLocked(const String8& cameraId,
2486 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
2498 }; // namespace android
2499