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 <stdio.h>
21 #include <string.h>
22 #include <sys/types.h>
23 #include <pthread.h>
24
25 #include <binder/AppOpsManager.h>
26 #include <binder/IPCThreadState.h>
27 #include <binder/IServiceManager.h>
28 #include <binder/MemoryBase.h>
29 #include <binder/MemoryHeapBase.h>
30 #include <cutils/atomic.h>
31 #include <cutils/properties.h>
32 #include <gui/Surface.h>
33 #include <hardware/hardware.h>
34 #include <media/AudioSystem.h>
35 #include <media/IMediaHTTPService.h>
36 #include <media/mediaplayer.h>
37 #include <utils/Errors.h>
38 #include <utils/Log.h>
39 #include <utils/String16.h>
40 #include <utils/Trace.h>
41 #include <system/camera_vendor_tags.h>
42 #include <system/camera_metadata.h>
43 #include <system/camera.h>
44
45 #include "CameraService.h"
46 #include "api1/CameraClient.h"
47 #include "api1/Camera2Client.h"
48 #include "api_pro/ProCamera2Client.h"
49 #include "api2/CameraDeviceClient.h"
50 #include "utils/CameraTraces.h"
51 #include "CameraDeviceFactory.h"
52
53 namespace android {
54
55 // ----------------------------------------------------------------------------
56 // Logging support -- this is for debugging only
57 // Use "adb shell dumpsys media.camera -v 1" to change it.
58 volatile int32_t gLogLevel = 0;
59
60 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
61 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
62
setLogLevel(int level)63 static void setLogLevel(int level) {
64 android_atomic_write(level, &gLogLevel);
65 }
66
67 // ----------------------------------------------------------------------------
68
getCallingPid()69 static int getCallingPid() {
70 return IPCThreadState::self()->getCallingPid();
71 }
72
getCallingUid()73 static int getCallingUid() {
74 return IPCThreadState::self()->getCallingUid();
75 }
76
77 extern "C" {
camera_device_status_change(const struct camera_module_callbacks * callbacks,int camera_id,int new_status)78 static void camera_device_status_change(
79 const struct camera_module_callbacks* callbacks,
80 int camera_id,
81 int new_status) {
82 sp<CameraService> cs = const_cast<CameraService*>(
83 static_cast<const CameraService*>(callbacks));
84
85 cs->onDeviceStatusChanged(
86 camera_id,
87 new_status);
88 }
89 } // extern "C"
90
91 // ----------------------------------------------------------------------------
92
93 // This is ugly and only safe if we never re-create the CameraService, but
94 // should be ok for now.
95 static CameraService *gCameraService;
96
CameraService()97 CameraService::CameraService()
98 :mSoundRef(0), mModule(0)
99 {
100 ALOGI("CameraService started (pid=%d)", getpid());
101 gCameraService = this;
102
103 for (size_t i = 0; i < MAX_CAMERAS; ++i) {
104 mStatusList[i] = ICameraServiceListener::STATUS_PRESENT;
105 }
106
107 this->camera_device_status_change = android::camera_device_status_change;
108 }
109
onFirstRef()110 void CameraService::onFirstRef()
111 {
112 LOG1("CameraService::onFirstRef");
113
114 BnCameraService::onFirstRef();
115
116 if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
117 (const hw_module_t **)&mModule) < 0) {
118 ALOGE("Could not load camera HAL module");
119 mNumberOfCameras = 0;
120 }
121 else {
122 ALOGI("Loaded \"%s\" camera module", mModule->common.name);
123 mNumberOfCameras = mModule->get_number_of_cameras();
124 if (mNumberOfCameras > MAX_CAMERAS) {
125 ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).",
126 mNumberOfCameras, MAX_CAMERAS);
127 mNumberOfCameras = MAX_CAMERAS;
128 }
129 for (int i = 0; i < mNumberOfCameras; i++) {
130 setCameraFree(i);
131 }
132
133 if (mModule->common.module_api_version >=
134 CAMERA_MODULE_API_VERSION_2_1) {
135 mModule->set_callbacks(this);
136 }
137
138 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
139
140 if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_2) {
141 setUpVendorTags();
142 }
143
144 CameraDeviceFactory::registerService(this);
145 }
146 }
147
~CameraService()148 CameraService::~CameraService() {
149 for (int i = 0; i < mNumberOfCameras; i++) {
150 if (mBusy[i]) {
151 ALOGE("camera %d is still in use in destructor!", i);
152 }
153 }
154
155 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
156 gCameraService = NULL;
157 }
158
onDeviceStatusChanged(int cameraId,int newStatus)159 void CameraService::onDeviceStatusChanged(int cameraId,
160 int newStatus)
161 {
162 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
163 cameraId, newStatus);
164
165 if (cameraId < 0 || cameraId >= MAX_CAMERAS) {
166 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
167 return;
168 }
169
170 if ((int)getStatus(cameraId) == newStatus) {
171 ALOGE("%s: State transition to the same status 0x%x not allowed",
172 __FUNCTION__, (uint32_t)newStatus);
173 return;
174 }
175
176 /* don't do this in updateStatus
177 since it is also called from connect and we could get into a deadlock */
178 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
179 Vector<sp<BasicClient> > clientsToDisconnect;
180 {
181 Mutex::Autolock al(mServiceLock);
182
183 /* Remove cached parameters from shim cache */
184 mShimParams.removeItem(cameraId);
185
186 /* Find all clients that we need to disconnect */
187 sp<BasicClient> client = mClient[cameraId].promote();
188 if (client.get() != NULL) {
189 clientsToDisconnect.push_back(client);
190 }
191
192 int i = cameraId;
193 for (size_t j = 0; j < mProClientList[i].size(); ++j) {
194 sp<ProClient> cl = mProClientList[i][j].promote();
195 if (cl != NULL) {
196 clientsToDisconnect.push_back(cl);
197 }
198 }
199 }
200
201 /* now disconnect them. don't hold the lock
202 or we can get into a deadlock */
203
204 for (size_t i = 0; i < clientsToDisconnect.size(); ++i) {
205 sp<BasicClient> client = clientsToDisconnect[i];
206
207 client->disconnect();
208 /**
209 * The remote app will no longer be able to call methods on the
210 * client since the client PID will be reset to 0
211 */
212 }
213
214 ALOGV("%s: After unplug, disconnected %zu clients",
215 __FUNCTION__, clientsToDisconnect.size());
216 }
217
218 updateStatus(
219 static_cast<ICameraServiceListener::Status>(newStatus), cameraId);
220
221 }
222
getNumberOfCameras()223 int32_t CameraService::getNumberOfCameras() {
224 return mNumberOfCameras;
225 }
226
getCameraInfo(int cameraId,struct CameraInfo * cameraInfo)227 status_t CameraService::getCameraInfo(int cameraId,
228 struct CameraInfo* cameraInfo) {
229 if (!mModule) {
230 return -ENODEV;
231 }
232
233 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
234 return BAD_VALUE;
235 }
236
237 struct camera_info info;
238 status_t rc = filterGetInfoErrorCode(
239 mModule->get_camera_info(cameraId, &info));
240 cameraInfo->facing = info.facing;
241 cameraInfo->orientation = info.orientation;
242 return rc;
243 }
244
245
generateShimMetadata(int cameraId,CameraMetadata * cameraInfo)246 status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
247 status_t ret = OK;
248 struct CameraInfo info;
249 if ((ret = getCameraInfo(cameraId, &info)) != OK) {
250 return ret;
251 }
252
253 CameraMetadata shimInfo;
254 int32_t orientation = static_cast<int32_t>(info.orientation);
255 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
256 return ret;
257 }
258
259 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
260 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
261 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
262 return ret;
263 }
264
265 CameraParameters shimParams;
266 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
267 // Error logged by callee
268 return ret;
269 }
270
271 Vector<Size> sizes;
272 Vector<Size> jpegSizes;
273 Vector<int32_t> formats;
274 const char* supportedPreviewFormats;
275 {
276 shimParams.getSupportedPreviewSizes(/*out*/sizes);
277 shimParams.getSupportedPreviewFormats(/*out*/formats);
278 shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
279 }
280
281 // Always include IMPLEMENTATION_DEFINED
282 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
283
284 const size_t INTS_PER_CONFIG = 4;
285
286 // Build available stream configurations metadata
287 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
288
289 Vector<int32_t> streamConfigs;
290 streamConfigs.setCapacity(streamConfigSize);
291
292 for (size_t i = 0; i < formats.size(); ++i) {
293 for (size_t j = 0; j < sizes.size(); ++j) {
294 streamConfigs.add(formats[i]);
295 streamConfigs.add(sizes[j].width);
296 streamConfigs.add(sizes[j].height);
297 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
298 }
299 }
300
301 for (size_t i = 0; i < jpegSizes.size(); ++i) {
302 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
303 streamConfigs.add(jpegSizes[i].width);
304 streamConfigs.add(jpegSizes[i].height);
305 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
306 }
307
308 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
309 streamConfigs.array(), streamConfigSize)) != OK) {
310 return ret;
311 }
312
313 int64_t fakeMinFrames[0];
314 // TODO: Fixme, don't fake min frame durations.
315 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
316 fakeMinFrames, 0)) != OK) {
317 return ret;
318 }
319
320 int64_t fakeStalls[0];
321 // TODO: Fixme, don't fake stall durations.
322 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
323 fakeStalls, 0)) != OK) {
324 return ret;
325 }
326
327 *cameraInfo = shimInfo;
328 return OK;
329 }
330
getCameraCharacteristics(int cameraId,CameraMetadata * cameraInfo)331 status_t CameraService::getCameraCharacteristics(int cameraId,
332 CameraMetadata* cameraInfo) {
333 if (!cameraInfo) {
334 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
335 return BAD_VALUE;
336 }
337
338 if (!mModule) {
339 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
340 return -ENODEV;
341 }
342
343 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
344 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
345 return BAD_VALUE;
346 }
347
348 int facing;
349 status_t ret = OK;
350 if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0 ||
351 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) {
352 /**
353 * Backwards compatibility mode for old HALs:
354 * - Convert CameraInfo into static CameraMetadata properties.
355 * - Retrieve cached CameraParameters for this camera. If none exist,
356 * attempt to open CameraClient and retrieve the CameraParameters.
357 * - Convert cached CameraParameters into static CameraMetadata
358 * properties.
359 */
360 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
361
362 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
363 return ret;
364 }
365
366 } else {
367 /**
368 * Normal HAL 2.1+ codepath.
369 */
370 struct camera_info info;
371 ret = filterGetInfoErrorCode(mModule->get_camera_info(cameraId, &info));
372 *cameraInfo = info.static_camera_characteristics;
373 }
374
375 return ret;
376 }
377
getCameraVendorTagDescriptor(sp<VendorTagDescriptor> & desc)378 status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
379 if (!mModule) {
380 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
381 return -ENODEV;
382 }
383
384 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
385 return OK;
386 }
387
getDeviceVersion(int cameraId,int * facing)388 int CameraService::getDeviceVersion(int cameraId, int* facing) {
389 struct camera_info info;
390 if (mModule->get_camera_info(cameraId, &info) != OK) {
391 return -1;
392 }
393
394 int deviceVersion;
395 if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_0) {
396 deviceVersion = info.device_version;
397 } else {
398 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
399 }
400
401 if (facing) {
402 *facing = info.facing;
403 }
404
405 return deviceVersion;
406 }
407
filterOpenErrorCode(status_t err)408 status_t CameraService::filterOpenErrorCode(status_t err) {
409 switch(err) {
410 case NO_ERROR:
411 case -EBUSY:
412 case -EINVAL:
413 case -EUSERS:
414 return err;
415 default:
416 break;
417 }
418 return -ENODEV;
419 }
420
filterGetInfoErrorCode(status_t err)421 status_t CameraService::filterGetInfoErrorCode(status_t err) {
422 switch(err) {
423 case NO_ERROR:
424 case -EINVAL:
425 return err;
426 default:
427 break;
428 }
429 return -ENODEV;
430 }
431
setUpVendorTags()432 bool CameraService::setUpVendorTags() {
433 vendor_tag_ops_t vOps = vendor_tag_ops_t();
434
435 // Check if vendor operations have been implemented
436 if (mModule->get_vendor_tag_ops == NULL) {
437 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
438 return false;
439 }
440
441 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
442 mModule->get_vendor_tag_ops(&vOps);
443 ATRACE_END();
444
445 // Ensure all vendor operations are present
446 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
447 vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
448 vOps.get_tag_type == NULL) {
449 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
450 , __FUNCTION__);
451 return false;
452 }
453
454 // Read all vendor tag definitions into a descriptor
455 sp<VendorTagDescriptor> desc;
456 status_t res;
457 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
458 != OK) {
459 ALOGE("%s: Could not generate descriptor from vendor tag operations,"
460 "received error %s (%d). Camera clients will not be able to use"
461 "vendor tags", __FUNCTION__, strerror(res), res);
462 return false;
463 }
464
465 // Set the global descriptor to use with camera metadata
466 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
467 return true;
468 }
469
initializeShimMetadata(int cameraId)470 status_t CameraService::initializeShimMetadata(int cameraId) {
471 int pid = getCallingPid();
472 int uid = getCallingUid();
473 status_t ret = validateConnect(cameraId, uid);
474 if (ret != OK) {
475 // Error already logged by callee
476 return ret;
477 }
478
479 bool needsNewClient = false;
480 sp<Client> client;
481
482 String16 internalPackageName("media");
483 { // Scope for service lock
484 Mutex::Autolock lock(mServiceLock);
485 if (mClient[cameraId] != NULL) {
486 client = static_cast<Client*>(mClient[cameraId].promote().get());
487 }
488 if (client == NULL) {
489 needsNewClient = true;
490 ret = connectHelperLocked(/*out*/client,
491 /*cameraClient*/NULL, // Empty binder callbacks
492 cameraId,
493 internalPackageName,
494 uid,
495 pid);
496
497 if (ret != OK) {
498 // Error already logged by callee
499 return ret;
500 }
501 }
502
503 if (client == NULL) {
504 ALOGE("%s: Could not connect to client camera device.", __FUNCTION__);
505 return BAD_VALUE;
506 }
507
508 String8 rawParams = client->getParameters();
509 CameraParameters params(rawParams);
510 mShimParams.add(cameraId, params);
511 }
512
513 // Close client if one was opened solely for this call
514 if (needsNewClient) {
515 client->disconnect();
516 }
517 return OK;
518 }
519
getLegacyParametersLazy(int cameraId,CameraParameters * parameters)520 status_t CameraService::getLegacyParametersLazy(int cameraId,
521 /*out*/
522 CameraParameters* parameters) {
523
524 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
525
526 status_t ret = 0;
527
528 if (parameters == NULL) {
529 ALOGE("%s: parameters must not be null", __FUNCTION__);
530 return BAD_VALUE;
531 }
532
533 ssize_t index = -1;
534 { // Scope for service lock
535 Mutex::Autolock lock(mServiceLock);
536 index = mShimParams.indexOfKey(cameraId);
537 // Release service lock so initializeShimMetadata can be called correctly.
538
539 if (index >= 0) {
540 *parameters = mShimParams[index];
541 }
542 }
543
544 if (index < 0) {
545 int64_t token = IPCThreadState::self()->clearCallingIdentity();
546 ret = initializeShimMetadata(cameraId);
547 IPCThreadState::self()->restoreCallingIdentity(token);
548 if (ret != OK) {
549 // Error already logged by callee
550 return ret;
551 }
552
553 { // Scope for service lock
554 Mutex::Autolock lock(mServiceLock);
555 index = mShimParams.indexOfKey(cameraId);
556
557 LOG_ALWAYS_FATAL_IF(index < 0, "index should have been initialized");
558
559 *parameters = mShimParams[index];
560 }
561 }
562
563 return OK;
564 }
565
validateConnect(int cameraId,int & clientUid) const566 status_t CameraService::validateConnect(int cameraId,
567 /*inout*/
568 int& clientUid) const {
569
570 int callingPid = getCallingPid();
571
572 if (clientUid == USE_CALLING_UID) {
573 clientUid = getCallingUid();
574 } else {
575 // We only trust our own process to forward client UIDs
576 if (callingPid != getpid()) {
577 ALOGE("CameraService::connect X (pid %d) rejected (don't trust clientUid)",
578 callingPid);
579 return PERMISSION_DENIED;
580 }
581 }
582
583 if (!mModule) {
584 ALOGE("Camera HAL module not loaded");
585 return -ENODEV;
586 }
587
588 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
589 ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
590 callingPid, cameraId);
591 return -ENODEV;
592 }
593
594 char value[PROPERTY_VALUE_MAX];
595 property_get("sys.secpolicy.camera.disabled", value, "0");
596 if (strcmp(value, "1") == 0) {
597 // Camera is disabled by DevicePolicyManager.
598 ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
599 return -EACCES;
600 }
601
602 ICameraServiceListener::Status currentStatus = getStatus(cameraId);
603 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
604 ALOGI("Camera is not plugged in,"
605 " connect X (pid %d) rejected", callingPid);
606 return -ENODEV;
607 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
608 ALOGI("Camera is enumerating,"
609 " connect X (pid %d) rejected", callingPid);
610 return -EBUSY;
611 }
612 // Else don't check for STATUS_NOT_AVAILABLE.
613 // -- It's done implicitly in canConnectUnsafe /w the mBusy array
614
615 return OK;
616 }
617
canConnectUnsafe(int cameraId,const String16 & clientPackageName,const sp<IBinder> & remoteCallback,sp<BasicClient> & client)618 bool CameraService::canConnectUnsafe(int cameraId,
619 const String16& clientPackageName,
620 const sp<IBinder>& remoteCallback,
621 sp<BasicClient> &client) {
622 String8 clientName8(clientPackageName);
623 int callingPid = getCallingPid();
624
625 if (mClient[cameraId] != 0) {
626 client = mClient[cameraId].promote();
627 if (client != 0) {
628 if (remoteCallback == client->getRemote()) {
629 LOG1("CameraService::connect X (pid %d) (the same client)",
630 callingPid);
631 return true;
632 } else {
633 // TODOSC: need to support 1 regular client,
634 // multiple shared clients here
635 ALOGW("CameraService::connect X (pid %d) rejected"
636 " (existing client).", callingPid);
637 return false;
638 }
639 }
640 mClient[cameraId].clear();
641 }
642
643 /*
644 mBusy is set to false as the last step of the Client destructor,
645 after which it is guaranteed that the Client destructor has finished (
646 including any inherited destructors)
647
648 We only need this for a Client subclasses since we don't allow
649 multiple Clents to be opened concurrently, but multiple BasicClient
650 would be fine
651 */
652 if (mBusy[cameraId]) {
653 ALOGW("CameraService::connect X (pid %d, \"%s\") rejected"
654 " (camera %d is still busy).", callingPid,
655 clientName8.string(), cameraId);
656 return false;
657 }
658
659 return true;
660 }
661
connectHelperLocked(sp<Client> & client,const sp<ICameraClient> & cameraClient,int cameraId,const String16 & clientPackageName,int clientUid,int callingPid,int halVersion,bool legacyMode)662 status_t CameraService::connectHelperLocked(
663 /*out*/
664 sp<Client>& client,
665 /*in*/
666 const sp<ICameraClient>& cameraClient,
667 int cameraId,
668 const String16& clientPackageName,
669 int clientUid,
670 int callingPid,
671 int halVersion,
672 bool legacyMode) {
673
674 int facing = -1;
675 int deviceVersion = getDeviceVersion(cameraId, &facing);
676
677 if (halVersion < 0 || halVersion == deviceVersion) {
678 // Default path: HAL version is unspecified by caller, create CameraClient
679 // based on device version reported by the HAL.
680 switch(deviceVersion) {
681 case CAMERA_DEVICE_API_VERSION_1_0:
682 client = new CameraClient(this, cameraClient,
683 clientPackageName, cameraId,
684 facing, callingPid, clientUid, getpid(), legacyMode);
685 break;
686 case CAMERA_DEVICE_API_VERSION_2_0:
687 case CAMERA_DEVICE_API_VERSION_2_1:
688 case CAMERA_DEVICE_API_VERSION_3_0:
689 case CAMERA_DEVICE_API_VERSION_3_1:
690 case CAMERA_DEVICE_API_VERSION_3_2:
691 client = new Camera2Client(this, cameraClient,
692 clientPackageName, cameraId,
693 facing, callingPid, clientUid, getpid(), legacyMode);
694 break;
695 case -1:
696 ALOGE("Invalid camera id %d", cameraId);
697 return BAD_VALUE;
698 default:
699 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
700 return INVALID_OPERATION;
701 }
702 } else {
703 // A particular HAL version is requested by caller. Create CameraClient
704 // based on the requested HAL version.
705 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
706 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
707 // Only support higher HAL version device opened as HAL1.0 device.
708 client = new CameraClient(this, cameraClient,
709 clientPackageName, cameraId,
710 facing, callingPid, clientUid, getpid(), legacyMode);
711 } else {
712 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
713 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
714 " opened as HAL %x device", halVersion, deviceVersion,
715 CAMERA_DEVICE_API_VERSION_1_0);
716 return INVALID_OPERATION;
717 }
718 }
719
720 status_t status = connectFinishUnsafe(client, client->getRemote());
721 if (status != OK) {
722 // this is probably not recoverable.. maybe the client can try again
723 return status;
724 }
725
726 mClient[cameraId] = client;
727 LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId,
728 getpid());
729
730 return OK;
731 }
732
connect(const sp<ICameraClient> & cameraClient,int cameraId,const String16 & clientPackageName,int clientUid,sp<ICamera> & device)733 status_t CameraService::connect(
734 const sp<ICameraClient>& cameraClient,
735 int cameraId,
736 const String16& clientPackageName,
737 int clientUid,
738 /*out*/
739 sp<ICamera>& device) {
740
741 String8 clientName8(clientPackageName);
742 int callingPid = getCallingPid();
743
744 LOG1("CameraService::connect E (pid %d \"%s\", id %d)", callingPid,
745 clientName8.string(), cameraId);
746
747 status_t status = validateConnect(cameraId, /*inout*/clientUid);
748 if (status != OK) {
749 return status;
750 }
751
752
753 sp<Client> client;
754 {
755 Mutex::Autolock lock(mServiceLock);
756 sp<BasicClient> clientTmp;
757 if (!canConnectUnsafe(cameraId, clientPackageName,
758 cameraClient->asBinder(),
759 /*out*/clientTmp)) {
760 return -EBUSY;
761 } else if (client.get() != NULL) {
762 device = static_cast<Client*>(clientTmp.get());
763 return OK;
764 }
765
766 status = connectHelperLocked(/*out*/client,
767 cameraClient,
768 cameraId,
769 clientPackageName,
770 clientUid,
771 callingPid);
772 if (status != OK) {
773 return status;
774 }
775
776 }
777 // important: release the mutex here so the client can call back
778 // into the service from its destructor (can be at the end of the call)
779
780 device = client;
781 return OK;
782 }
783
connectLegacy(const sp<ICameraClient> & cameraClient,int cameraId,int halVersion,const String16 & clientPackageName,int clientUid,sp<ICamera> & device)784 status_t CameraService::connectLegacy(
785 const sp<ICameraClient>& cameraClient,
786 int cameraId, int halVersion,
787 const String16& clientPackageName,
788 int clientUid,
789 /*out*/
790 sp<ICamera>& device) {
791
792 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
793 mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_3) {
794 /*
795 * Either the HAL version is unspecified in which case this just creates
796 * a camera client selected by the latest device version, or
797 * it's a particular version in which case the HAL must supported
798 * the open_legacy call
799 */
800 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
801 __FUNCTION__, mModule->common.module_api_version);
802 return INVALID_OPERATION;
803 }
804
805 String8 clientName8(clientPackageName);
806 int callingPid = getCallingPid();
807
808 LOG1("CameraService::connect legacy E (pid %d \"%s\", id %d)", callingPid,
809 clientName8.string(), cameraId);
810
811 status_t status = validateConnect(cameraId, /*inout*/clientUid);
812 if (status != OK) {
813 return status;
814 }
815
816 sp<Client> client;
817 {
818 Mutex::Autolock lock(mServiceLock);
819 sp<BasicClient> clientTmp;
820 if (!canConnectUnsafe(cameraId, clientPackageName,
821 cameraClient->asBinder(),
822 /*out*/clientTmp)) {
823 return -EBUSY;
824 } else if (client.get() != NULL) {
825 device = static_cast<Client*>(clientTmp.get());
826 return OK;
827 }
828
829 status = connectHelperLocked(/*out*/client,
830 cameraClient,
831 cameraId,
832 clientPackageName,
833 clientUid,
834 callingPid,
835 halVersion,
836 /*legacyMode*/true);
837 if (status != OK) {
838 return status;
839 }
840
841 }
842 // important: release the mutex here so the client can call back
843 // into the service from its destructor (can be at the end of the call)
844
845 device = client;
846 return OK;
847 }
848
connectFinishUnsafe(const sp<BasicClient> & client,const sp<IBinder> & remoteCallback)849 status_t CameraService::connectFinishUnsafe(const sp<BasicClient>& client,
850 const sp<IBinder>& remoteCallback) {
851 status_t status = client->initialize(mModule);
852 if (status != OK) {
853 ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
854 return status;
855 }
856 if (remoteCallback != NULL) {
857 remoteCallback->linkToDeath(this);
858 }
859
860 return OK;
861 }
862
connectPro(const sp<IProCameraCallbacks> & cameraCb,int cameraId,const String16 & clientPackageName,int clientUid,sp<IProCameraUser> & device)863 status_t CameraService::connectPro(
864 const sp<IProCameraCallbacks>& cameraCb,
865 int cameraId,
866 const String16& clientPackageName,
867 int clientUid,
868 /*out*/
869 sp<IProCameraUser>& device)
870 {
871 if (cameraCb == 0) {
872 ALOGE("%s: Callback must not be null", __FUNCTION__);
873 return BAD_VALUE;
874 }
875
876 String8 clientName8(clientPackageName);
877 int callingPid = getCallingPid();
878
879 LOG1("CameraService::connectPro E (pid %d \"%s\", id %d)", callingPid,
880 clientName8.string(), cameraId);
881 status_t status = validateConnect(cameraId, /*inout*/clientUid);
882 if (status != OK) {
883 return status;
884 }
885
886 sp<ProClient> client;
887 {
888 Mutex::Autolock lock(mServiceLock);
889 {
890 sp<BasicClient> client;
891 if (!canConnectUnsafe(cameraId, clientPackageName,
892 cameraCb->asBinder(),
893 /*out*/client)) {
894 return -EBUSY;
895 }
896 }
897
898 int facing = -1;
899 int deviceVersion = getDeviceVersion(cameraId, &facing);
900
901 switch(deviceVersion) {
902 case CAMERA_DEVICE_API_VERSION_1_0:
903 ALOGE("Camera id %d uses HALv1, doesn't support ProCamera",
904 cameraId);
905 return -EOPNOTSUPP;
906 break;
907 case CAMERA_DEVICE_API_VERSION_2_0:
908 case CAMERA_DEVICE_API_VERSION_2_1:
909 case CAMERA_DEVICE_API_VERSION_3_0:
910 case CAMERA_DEVICE_API_VERSION_3_1:
911 case CAMERA_DEVICE_API_VERSION_3_2:
912 client = new ProCamera2Client(this, cameraCb, clientPackageName,
913 cameraId, facing, callingPid, clientUid, getpid());
914 break;
915 case -1:
916 ALOGE("Invalid camera id %d", cameraId);
917 return BAD_VALUE;
918 default:
919 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
920 return INVALID_OPERATION;
921 }
922
923 status_t status = connectFinishUnsafe(client, client->getRemote());
924 if (status != OK) {
925 return status;
926 }
927
928 mProClientList[cameraId].push(client);
929
930 LOG1("CameraService::connectPro X (id %d, this pid is %d)", cameraId,
931 getpid());
932 }
933 // important: release the mutex here so the client can call back
934 // into the service from its destructor (can be at the end of the call)
935 device = client;
936 return OK;
937 }
938
connectDevice(const sp<ICameraDeviceCallbacks> & cameraCb,int cameraId,const String16 & clientPackageName,int clientUid,sp<ICameraDeviceUser> & device)939 status_t CameraService::connectDevice(
940 const sp<ICameraDeviceCallbacks>& cameraCb,
941 int cameraId,
942 const String16& clientPackageName,
943 int clientUid,
944 /*out*/
945 sp<ICameraDeviceUser>& device)
946 {
947
948 String8 clientName8(clientPackageName);
949 int callingPid = getCallingPid();
950
951 LOG1("CameraService::connectDevice E (pid %d \"%s\", id %d)", callingPid,
952 clientName8.string(), cameraId);
953
954 status_t status = validateConnect(cameraId, /*inout*/clientUid);
955 if (status != OK) {
956 return status;
957 }
958
959 sp<CameraDeviceClient> client;
960 {
961 Mutex::Autolock lock(mServiceLock);
962 {
963 sp<BasicClient> client;
964 if (!canConnectUnsafe(cameraId, clientPackageName,
965 cameraCb->asBinder(),
966 /*out*/client)) {
967 return -EBUSY;
968 }
969 }
970
971 int facing = -1;
972 int deviceVersion = getDeviceVersion(cameraId, &facing);
973
974 switch(deviceVersion) {
975 case CAMERA_DEVICE_API_VERSION_1_0:
976 ALOGW("Camera using old HAL version: %d", deviceVersion);
977 return -EOPNOTSUPP;
978 // TODO: don't allow 2.0 Only allow 2.1 and higher
979 case CAMERA_DEVICE_API_VERSION_2_0:
980 case CAMERA_DEVICE_API_VERSION_2_1:
981 case CAMERA_DEVICE_API_VERSION_3_0:
982 case CAMERA_DEVICE_API_VERSION_3_1:
983 case CAMERA_DEVICE_API_VERSION_3_2:
984 client = new CameraDeviceClient(this, cameraCb, clientPackageName,
985 cameraId, facing, callingPid, clientUid, getpid());
986 break;
987 case -1:
988 ALOGE("Invalid camera id %d", cameraId);
989 return BAD_VALUE;
990 default:
991 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
992 return INVALID_OPERATION;
993 }
994
995 status_t status = connectFinishUnsafe(client, client->getRemote());
996 if (status != OK) {
997 // this is probably not recoverable.. maybe the client can try again
998 return status;
999 }
1000
1001 LOG1("CameraService::connectDevice X (id %d, this pid is %d)", cameraId,
1002 getpid());
1003
1004 mClient[cameraId] = client;
1005 }
1006 // important: release the mutex here so the client can call back
1007 // into the service from its destructor (can be at the end of the call)
1008
1009 device = client;
1010 return OK;
1011 }
1012
1013
addListener(const sp<ICameraServiceListener> & listener)1014 status_t CameraService::addListener(
1015 const sp<ICameraServiceListener>& listener) {
1016 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1017
1018 if (listener == 0) {
1019 ALOGE("%s: Listener must not be null", __FUNCTION__);
1020 return BAD_VALUE;
1021 }
1022
1023 Mutex::Autolock lock(mServiceLock);
1024
1025 Vector<sp<ICameraServiceListener> >::iterator it, end;
1026 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
1027 if ((*it)->asBinder() == listener->asBinder()) {
1028 ALOGW("%s: Tried to add listener %p which was already subscribed",
1029 __FUNCTION__, listener.get());
1030 return ALREADY_EXISTS;
1031 }
1032 }
1033
1034 mListenerList.push_back(listener);
1035
1036 /* Immediately signal current status to this listener only */
1037 {
1038 Mutex::Autolock m(mStatusMutex) ;
1039 int numCams = getNumberOfCameras();
1040 for (int i = 0; i < numCams; ++i) {
1041 listener->onStatusChanged(mStatusList[i], i);
1042 }
1043 }
1044
1045 return OK;
1046 }
removeListener(const sp<ICameraServiceListener> & listener)1047 status_t CameraService::removeListener(
1048 const sp<ICameraServiceListener>& listener) {
1049 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1050
1051 if (listener == 0) {
1052 ALOGE("%s: Listener must not be null", __FUNCTION__);
1053 return BAD_VALUE;
1054 }
1055
1056 Mutex::Autolock lock(mServiceLock);
1057
1058 Vector<sp<ICameraServiceListener> >::iterator it;
1059 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
1060 if ((*it)->asBinder() == listener->asBinder()) {
1061 mListenerList.erase(it);
1062 return OK;
1063 }
1064 }
1065
1066 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1067 __FUNCTION__, listener.get());
1068
1069 return BAD_VALUE;
1070 }
1071
getLegacyParameters(int cameraId,String16 * parameters)1072 status_t CameraService::getLegacyParameters(
1073 int cameraId,
1074 /*out*/
1075 String16* parameters) {
1076 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1077
1078 if (parameters == NULL) {
1079 ALOGE("%s: parameters must not be null", __FUNCTION__);
1080 return BAD_VALUE;
1081 }
1082
1083 status_t ret = 0;
1084
1085 CameraParameters shimParams;
1086 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1087 // Error logged by caller
1088 return ret;
1089 }
1090
1091 String8 shimParamsString8 = shimParams.flatten();
1092 String16 shimParamsString16 = String16(shimParamsString8);
1093
1094 *parameters = shimParamsString16;
1095
1096 return OK;
1097 }
1098
supportsCameraApi(int cameraId,int apiVersion)1099 status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1100 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1101
1102 switch (apiVersion) {
1103 case API_VERSION_1:
1104 case API_VERSION_2:
1105 break;
1106 default:
1107 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1108 return BAD_VALUE;
1109 }
1110
1111 int facing = -1;
1112 int deviceVersion = getDeviceVersion(cameraId, &facing);
1113
1114 switch(deviceVersion) {
1115 case CAMERA_DEVICE_API_VERSION_1_0:
1116 case CAMERA_DEVICE_API_VERSION_2_0:
1117 case CAMERA_DEVICE_API_VERSION_2_1:
1118 case CAMERA_DEVICE_API_VERSION_3_0:
1119 case CAMERA_DEVICE_API_VERSION_3_1:
1120 if (apiVersion == API_VERSION_2) {
1121 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1122 __FUNCTION__, cameraId);
1123 return -EOPNOTSUPP;
1124 } else { // if (apiVersion == API_VERSION_1) {
1125 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1126 __FUNCTION__, cameraId);
1127 return OK;
1128 }
1129 case CAMERA_DEVICE_API_VERSION_3_2:
1130 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1131 __FUNCTION__, cameraId);
1132 return OK;
1133 case -1:
1134 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1135 return BAD_VALUE;
1136 default:
1137 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1138 return INVALID_OPERATION;
1139 }
1140
1141 return OK;
1142 }
1143
removeClientByRemote(const wp<IBinder> & remoteBinder)1144 void CameraService::removeClientByRemote(const wp<IBinder>& remoteBinder) {
1145 int callingPid = getCallingPid();
1146 LOG1("CameraService::removeClientByRemote E (pid %d)", callingPid);
1147
1148 // Declare this before the lock to make absolutely sure the
1149 // destructor won't be called with the lock held.
1150 Mutex::Autolock lock(mServiceLock);
1151
1152 int outIndex;
1153 sp<BasicClient> client = findClientUnsafe(remoteBinder, outIndex);
1154
1155 if (client != 0) {
1156 // Found our camera, clear and leave.
1157 LOG1("removeClient: clear camera %d", outIndex);
1158
1159 sp<IBinder> remote = client->getRemote();
1160 if (remote != NULL) {
1161 remote->unlinkToDeath(this);
1162 }
1163
1164 mClient[outIndex].clear();
1165 } else {
1166
1167 sp<ProClient> clientPro = findProClientUnsafe(remoteBinder);
1168
1169 if (clientPro != NULL) {
1170 // Found our camera, clear and leave.
1171 LOG1("removeClient: clear pro %p", clientPro.get());
1172
1173 clientPro->getRemoteCallback()->asBinder()->unlinkToDeath(this);
1174 }
1175 }
1176
1177 LOG1("CameraService::removeClientByRemote X (pid %d)", callingPid);
1178 }
1179
findProClientUnsafe(const wp<IBinder> & cameraCallbacksRemote)1180 sp<CameraService::ProClient> CameraService::findProClientUnsafe(
1181 const wp<IBinder>& cameraCallbacksRemote)
1182 {
1183 sp<ProClient> clientPro;
1184
1185 for (int i = 0; i < mNumberOfCameras; ++i) {
1186 Vector<size_t> removeIdx;
1187
1188 for (size_t j = 0; j < mProClientList[i].size(); ++j) {
1189 wp<ProClient> cl = mProClientList[i][j];
1190
1191 sp<ProClient> clStrong = cl.promote();
1192 if (clStrong != NULL && clStrong->getRemote() == cameraCallbacksRemote) {
1193 clientPro = clStrong;
1194 break;
1195 } else if (clStrong == NULL) {
1196 // mark to clean up dead ptr
1197 removeIdx.push(j);
1198 }
1199 }
1200
1201 // remove stale ptrs (in reverse so the indices dont change)
1202 for (ssize_t j = (ssize_t)removeIdx.size() - 1; j >= 0; --j) {
1203 mProClientList[i].removeAt(removeIdx[j]);
1204 }
1205
1206 }
1207
1208 return clientPro;
1209 }
1210
findClientUnsafe(const wp<IBinder> & cameraClient,int & outIndex)1211 sp<CameraService::BasicClient> CameraService::findClientUnsafe(
1212 const wp<IBinder>& cameraClient, int& outIndex) {
1213 sp<BasicClient> client;
1214
1215 for (int i = 0; i < mNumberOfCameras; i++) {
1216
1217 // This happens when we have already disconnected (or this is
1218 // just another unused camera).
1219 if (mClient[i] == 0) continue;
1220
1221 // Promote mClient. It can fail if we are called from this path:
1222 // Client::~Client() -> disconnect() -> removeClientByRemote().
1223 client = mClient[i].promote();
1224
1225 // Clean up stale client entry
1226 if (client == NULL) {
1227 mClient[i].clear();
1228 continue;
1229 }
1230
1231 if (cameraClient == client->getRemote()) {
1232 // Found our camera
1233 outIndex = i;
1234 return client;
1235 }
1236 }
1237
1238 outIndex = -1;
1239 return NULL;
1240 }
1241
getClientByIdUnsafe(int cameraId)1242 CameraService::BasicClient* CameraService::getClientByIdUnsafe(int cameraId) {
1243 if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
1244 return mClient[cameraId].unsafe_get();
1245 }
1246
getClientLockById(int cameraId)1247 Mutex* CameraService::getClientLockById(int cameraId) {
1248 if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
1249 return &mClientLock[cameraId];
1250 }
1251
getClientByRemote(const wp<IBinder> & cameraClient)1252 sp<CameraService::BasicClient> CameraService::getClientByRemote(
1253 const wp<IBinder>& cameraClient) {
1254
1255 // Declare this before the lock to make absolutely sure the
1256 // destructor won't be called with the lock held.
1257 sp<BasicClient> client;
1258
1259 Mutex::Autolock lock(mServiceLock);
1260
1261 int outIndex;
1262 client = findClientUnsafe(cameraClient, outIndex);
1263
1264 return client;
1265 }
1266
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1267 status_t CameraService::onTransact(
1268 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
1269 // Permission checks
1270 switch (code) {
1271 case BnCameraService::CONNECT:
1272 case BnCameraService::CONNECT_PRO:
1273 case BnCameraService::CONNECT_DEVICE:
1274 case BnCameraService::CONNECT_LEGACY:
1275 const int pid = getCallingPid();
1276 const int self_pid = getpid();
1277 if (pid != self_pid) {
1278 // we're called from a different process, do the real check
1279 if (!checkCallingPermission(
1280 String16("android.permission.CAMERA"))) {
1281 const int uid = getCallingUid();
1282 ALOGE("Permission Denial: "
1283 "can't use the camera pid=%d, uid=%d", pid, uid);
1284 return PERMISSION_DENIED;
1285 }
1286 }
1287 break;
1288 }
1289
1290 return BnCameraService::onTransact(code, data, reply, flags);
1291 }
1292
1293 // The reason we need this busy bit is a new CameraService::connect() request
1294 // may come in while the previous Client's destructor has not been run or is
1295 // still running. If the last strong reference of the previous Client is gone
1296 // but the destructor has not been finished, we should not allow the new Client
1297 // to be created because we need to wait for the previous Client to tear down
1298 // the hardware first.
setCameraBusy(int cameraId)1299 void CameraService::setCameraBusy(int cameraId) {
1300 android_atomic_write(1, &mBusy[cameraId]);
1301
1302 ALOGV("setCameraBusy cameraId=%d", cameraId);
1303 }
1304
setCameraFree(int cameraId)1305 void CameraService::setCameraFree(int cameraId) {
1306 android_atomic_write(0, &mBusy[cameraId]);
1307
1308 ALOGV("setCameraFree cameraId=%d", cameraId);
1309 }
1310
1311 // We share the media players for shutter and recording sound for all clients.
1312 // A reference count is kept to determine when we will actually release the
1313 // media players.
1314
newMediaPlayer(const char * file)1315 MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1316 MediaPlayer* mp = new MediaPlayer();
1317 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1318 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1319 mp->prepare();
1320 } else {
1321 ALOGE("Failed to load CameraService sounds: %s", file);
1322 return NULL;
1323 }
1324 return mp;
1325 }
1326
loadSound()1327 void CameraService::loadSound() {
1328 Mutex::Autolock lock(mSoundLock);
1329 LOG1("CameraService::loadSound ref=%d", mSoundRef);
1330 if (mSoundRef++) return;
1331
1332 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1333 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1334 }
1335
releaseSound()1336 void CameraService::releaseSound() {
1337 Mutex::Autolock lock(mSoundLock);
1338 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1339 if (--mSoundRef) return;
1340
1341 for (int i = 0; i < NUM_SOUNDS; i++) {
1342 if (mSoundPlayer[i] != 0) {
1343 mSoundPlayer[i]->disconnect();
1344 mSoundPlayer[i].clear();
1345 }
1346 }
1347 }
1348
playSound(sound_kind kind)1349 void CameraService::playSound(sound_kind kind) {
1350 LOG1("playSound(%d)", kind);
1351 Mutex::Autolock lock(mSoundLock);
1352 sp<MediaPlayer> player = mSoundPlayer[kind];
1353 if (player != 0) {
1354 player->seekTo(0);
1355 player->start();
1356 }
1357 }
1358
1359 // ----------------------------------------------------------------------------
1360
Client(const sp<CameraService> & cameraService,const sp<ICameraClient> & cameraClient,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)1361 CameraService::Client::Client(const sp<CameraService>& cameraService,
1362 const sp<ICameraClient>& cameraClient,
1363 const String16& clientPackageName,
1364 int cameraId, int cameraFacing,
1365 int clientPid, uid_t clientUid,
1366 int servicePid) :
1367 CameraService::BasicClient(cameraService, cameraClient->asBinder(),
1368 clientPackageName,
1369 cameraId, cameraFacing,
1370 clientPid, clientUid,
1371 servicePid)
1372 {
1373 int callingPid = getCallingPid();
1374 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
1375
1376 mRemoteCallback = cameraClient;
1377
1378 cameraService->setCameraBusy(cameraId);
1379 cameraService->loadSound();
1380
1381 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
1382 }
1383
1384 // tear down the client
~Client()1385 CameraService::Client::~Client() {
1386 ALOGV("~Client");
1387 mDestructionStarted = true;
1388
1389 mCameraService->releaseSound();
1390 // unconditionally disconnect. function is idempotent
1391 Client::disconnect();
1392 }
1393
BasicClient(const sp<CameraService> & cameraService,const sp<IBinder> & remoteCallback,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)1394 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
1395 const sp<IBinder>& remoteCallback,
1396 const String16& clientPackageName,
1397 int cameraId, int cameraFacing,
1398 int clientPid, uid_t clientUid,
1399 int servicePid):
1400 mClientPackageName(clientPackageName)
1401 {
1402 mCameraService = cameraService;
1403 mRemoteBinder = remoteCallback;
1404 mCameraId = cameraId;
1405 mCameraFacing = cameraFacing;
1406 mClientPid = clientPid;
1407 mClientUid = clientUid;
1408 mServicePid = servicePid;
1409 mOpsActive = false;
1410 mDestructionStarted = false;
1411 }
1412
~BasicClient()1413 CameraService::BasicClient::~BasicClient() {
1414 ALOGV("~BasicClient");
1415 mDestructionStarted = true;
1416 }
1417
disconnect()1418 void CameraService::BasicClient::disconnect() {
1419 ALOGV("BasicClient::disconnect");
1420 mCameraService->removeClientByRemote(mRemoteBinder);
1421
1422 finishCameraOps();
1423 // client shouldn't be able to call into us anymore
1424 mClientPid = 0;
1425 }
1426
startCameraOps()1427 status_t CameraService::BasicClient::startCameraOps() {
1428 int32_t res;
1429 // Notify app ops that the camera is not available
1430 mOpsCallback = new OpsCallback(this);
1431
1432 {
1433 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1434 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1435 }
1436
1437 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1438 mClientPackageName, mOpsCallback);
1439 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1440 mClientUid, mClientPackageName);
1441
1442 if (res != AppOpsManager::MODE_ALLOWED) {
1443 ALOGI("Camera %d: Access for \"%s\" has been revoked",
1444 mCameraId, String8(mClientPackageName).string());
1445 return PERMISSION_DENIED;
1446 }
1447
1448 mOpsActive = true;
1449
1450 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1451 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
1452 mCameraId);
1453
1454 return OK;
1455 }
1456
finishCameraOps()1457 status_t CameraService::BasicClient::finishCameraOps() {
1458 // Check if startCameraOps succeeded, and if so, finish the camera op
1459 if (mOpsActive) {
1460 // Notify app ops that the camera is available again
1461 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1462 mClientPackageName);
1463 mOpsActive = false;
1464
1465 // Notify device availability listeners that this camera is available
1466 // again
1467
1468 StatusVector rejectSourceStates;
1469 rejectSourceStates.push_back(ICameraServiceListener::STATUS_NOT_PRESENT);
1470 rejectSourceStates.push_back(ICameraServiceListener::STATUS_ENUMERATING);
1471
1472 // Transition to PRESENT if the camera is not in either of above 2
1473 // states
1474 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
1475 mCameraId,
1476 &rejectSourceStates);
1477
1478 }
1479 // Always stop watching, even if no camera op is active
1480 mAppOpsManager.stopWatchingMode(mOpsCallback);
1481 mOpsCallback.clear();
1482
1483 return OK;
1484 }
1485
opChanged(int32_t op,const String16 & packageName)1486 void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1487 String8 name(packageName);
1488 String8 myName(mClientPackageName);
1489
1490 if (op != AppOpsManager::OP_CAMERA) {
1491 ALOGW("Unexpected app ops notification received: %d", op);
1492 return;
1493 }
1494
1495 int32_t res;
1496 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1497 mClientUid, mClientPackageName);
1498 ALOGV("checkOp returns: %d, %s ", res,
1499 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1500 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1501 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1502 "UNKNOWN");
1503
1504 if (res != AppOpsManager::MODE_ALLOWED) {
1505 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1506 myName.string());
1507 // Reset the client PID to allow server-initiated disconnect,
1508 // and to prevent further calls by client.
1509 mClientPid = getCallingPid();
1510 CaptureResultExtras resultExtras; // a dummy result (invalid)
1511 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
1512 disconnect();
1513 }
1514 }
1515
1516 // ----------------------------------------------------------------------------
1517
getClientLockFromCookie(void * user)1518 Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
1519 return gCameraService->getClientLockById((int)(intptr_t) user);
1520 }
1521
1522 // Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
1523 // be acquired for this to be safe
getClientFromCookie(void * user)1524 CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
1525 BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int)(intptr_t) user);
1526 // OK: only CameraClient calls this, and they already cast anyway.
1527 Client* client = static_cast<Client*>(basicClient);
1528
1529 // This could happen if the Client is in the process of shutting down (the
1530 // last strong reference is gone, but the destructor hasn't finished
1531 // stopping the hardware).
1532 if (client == NULL) return NULL;
1533
1534 // destruction already started, so should not be accessed
1535 if (client->mDestructionStarted) return NULL;
1536
1537 return client;
1538 }
1539
notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,const CaptureResultExtras & resultExtras)1540 void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1541 const CaptureResultExtras& resultExtras) {
1542 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1543 }
1544
1545 // NOTE: function is idempotent
disconnect()1546 void CameraService::Client::disconnect() {
1547 ALOGV("Client::disconnect");
1548 BasicClient::disconnect();
1549 mCameraService->setCameraFree(mCameraId);
1550 }
1551
OpsCallback(wp<BasicClient> client)1552 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1553 mClient(client) {
1554 }
1555
opChanged(int32_t op,const String16 & packageName)1556 void CameraService::Client::OpsCallback::opChanged(int32_t op,
1557 const String16& packageName) {
1558 sp<BasicClient> client = mClient.promote();
1559 if (client != NULL) {
1560 client->opChanged(op, packageName);
1561 }
1562 }
1563
1564 // ----------------------------------------------------------------------------
1565 // IProCamera
1566 // ----------------------------------------------------------------------------
1567
ProClient(const sp<CameraService> & cameraService,const sp<IProCameraCallbacks> & remoteCallback,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)1568 CameraService::ProClient::ProClient(const sp<CameraService>& cameraService,
1569 const sp<IProCameraCallbacks>& remoteCallback,
1570 const String16& clientPackageName,
1571 int cameraId,
1572 int cameraFacing,
1573 int clientPid,
1574 uid_t clientUid,
1575 int servicePid)
1576 : CameraService::BasicClient(cameraService, remoteCallback->asBinder(),
1577 clientPackageName, cameraId, cameraFacing,
1578 clientPid, clientUid, servicePid)
1579 {
1580 mRemoteCallback = remoteCallback;
1581 }
1582
~ProClient()1583 CameraService::ProClient::~ProClient() {
1584 }
1585
notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,const CaptureResultExtras & resultExtras)1586 void CameraService::ProClient::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1587 const CaptureResultExtras& resultExtras) {
1588 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1589 }
1590
1591 // ----------------------------------------------------------------------------
1592
1593 static const int kDumpLockRetries = 50;
1594 static const int kDumpLockSleep = 60000;
1595
tryLock(Mutex & mutex)1596 static bool tryLock(Mutex& mutex)
1597 {
1598 bool locked = false;
1599 for (int i = 0; i < kDumpLockRetries; ++i) {
1600 if (mutex.tryLock() == NO_ERROR) {
1601 locked = true;
1602 break;
1603 }
1604 usleep(kDumpLockSleep);
1605 }
1606 return locked;
1607 }
1608
dump(int fd,const Vector<String16> & args)1609 status_t CameraService::dump(int fd, const Vector<String16>& args) {
1610 String8 result;
1611 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1612 result.appendFormat("Permission Denial: "
1613 "can't dump CameraService from pid=%d, uid=%d\n",
1614 getCallingPid(),
1615 getCallingUid());
1616 write(fd, result.string(), result.size());
1617 } else {
1618 bool locked = tryLock(mServiceLock);
1619 // failed to lock - CameraService is probably deadlocked
1620 if (!locked) {
1621 result.append("CameraService may be deadlocked\n");
1622 write(fd, result.string(), result.size());
1623 }
1624
1625 bool hasClient = false;
1626 if (!mModule) {
1627 result = String8::format("No camera module available!\n");
1628 write(fd, result.string(), result.size());
1629 if (locked) mServiceLock.unlock();
1630 return NO_ERROR;
1631 }
1632
1633 result = String8::format("Camera module HAL API version: 0x%x\n",
1634 mModule->common.hal_api_version);
1635 result.appendFormat("Camera module API version: 0x%x\n",
1636 mModule->common.module_api_version);
1637 result.appendFormat("Camera module name: %s\n",
1638 mModule->common.name);
1639 result.appendFormat("Camera module author: %s\n",
1640 mModule->common.author);
1641 result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
1642
1643 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1644 if (desc == NULL) {
1645 result.appendFormat("Vendor tags left unimplemented.\n");
1646 } else {
1647 result.appendFormat("Vendor tag definitions:\n");
1648 }
1649
1650 write(fd, result.string(), result.size());
1651
1652 if (desc != NULL) {
1653 desc->dump(fd, /*verbosity*/2, /*indentation*/4);
1654 }
1655
1656 for (int i = 0; i < mNumberOfCameras; i++) {
1657 result = String8::format("Camera %d static information:\n", i);
1658 camera_info info;
1659
1660 status_t rc = mModule->get_camera_info(i, &info);
1661 if (rc != OK) {
1662 result.appendFormat(" Error reading static information!\n");
1663 write(fd, result.string(), result.size());
1664 } else {
1665 result.appendFormat(" Facing: %s\n",
1666 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
1667 result.appendFormat(" Orientation: %d\n", info.orientation);
1668 int deviceVersion;
1669 if (mModule->common.module_api_version <
1670 CAMERA_MODULE_API_VERSION_2_0) {
1671 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
1672 } else {
1673 deviceVersion = info.device_version;
1674 }
1675 result.appendFormat(" Device version: 0x%x\n", deviceVersion);
1676 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
1677 result.appendFormat(" Device static metadata:\n");
1678 write(fd, result.string(), result.size());
1679 dump_indented_camera_metadata(info.static_camera_characteristics,
1680 fd, /*verbosity*/2, /*indentation*/4);
1681 } else {
1682 write(fd, result.string(), result.size());
1683 }
1684 }
1685
1686 sp<BasicClient> client = mClient[i].promote();
1687 if (client == 0) {
1688 result = String8::format(" Device is closed, no client instance\n");
1689 write(fd, result.string(), result.size());
1690 continue;
1691 }
1692 hasClient = true;
1693 result = String8::format(" Device is open. Client instance dump:\n");
1694 write(fd, result.string(), result.size());
1695 client->dump(fd, args);
1696 }
1697 if (!hasClient) {
1698 result = String8::format("\nNo active camera clients yet.\n");
1699 write(fd, result.string(), result.size());
1700 }
1701
1702 if (locked) mServiceLock.unlock();
1703
1704 // Dump camera traces if there were any
1705 write(fd, "\n", 1);
1706 camera3::CameraTraces::dump(fd, args);
1707
1708 // change logging level
1709 int n = args.size();
1710 for (int i = 0; i + 1 < n; i++) {
1711 String16 verboseOption("-v");
1712 if (args[i] == verboseOption) {
1713 String8 levelStr(args[i+1]);
1714 int level = atoi(levelStr.string());
1715 result = String8::format("\nSetting log level to %d.\n", level);
1716 setLogLevel(level);
1717 write(fd, result.string(), result.size());
1718 }
1719 }
1720
1721 }
1722 return NO_ERROR;
1723 }
1724
binderDied(const wp<IBinder> & who)1725 /*virtual*/void CameraService::binderDied(
1726 const wp<IBinder> &who) {
1727
1728 /**
1729 * While tempting to promote the wp<IBinder> into a sp,
1730 * it's actually not supported by the binder driver
1731 */
1732
1733 ALOGV("java clients' binder died");
1734
1735 sp<BasicClient> cameraClient = getClientByRemote(who);
1736
1737 if (cameraClient == 0) {
1738 ALOGV("java clients' binder death already cleaned up (normal case)");
1739 return;
1740 }
1741
1742 ALOGW("Disconnecting camera client %p since the binder for it "
1743 "died (this pid %d)", cameraClient.get(), getCallingPid());
1744
1745 cameraClient->disconnect();
1746
1747 }
1748
updateStatus(ICameraServiceListener::Status status,int32_t cameraId,const StatusVector * rejectSourceStates)1749 void CameraService::updateStatus(ICameraServiceListener::Status status,
1750 int32_t cameraId,
1751 const StatusVector *rejectSourceStates) {
1752 // do not lock mServiceLock here or can get into a deadlock from
1753 // connect() -> ProClient::disconnect -> updateStatus
1754 Mutex::Autolock lock(mStatusMutex);
1755
1756 ICameraServiceListener::Status oldStatus = mStatusList[cameraId];
1757
1758 mStatusList[cameraId] = status;
1759
1760 if (oldStatus != status) {
1761 ALOGV("%s: Status has changed for camera ID %d from 0x%x to 0x%x",
1762 __FUNCTION__, cameraId, (uint32_t)oldStatus, (uint32_t)status);
1763
1764 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
1765 (status != ICameraServiceListener::STATUS_PRESENT &&
1766 status != ICameraServiceListener::STATUS_ENUMERATING)) {
1767
1768 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT"
1769 " or ENUMERATING", __FUNCTION__);
1770 mStatusList[cameraId] = oldStatus;
1771 return;
1772 }
1773
1774 if (rejectSourceStates != NULL) {
1775 const StatusVector &rejectList = *rejectSourceStates;
1776 StatusVector::const_iterator it = rejectList.begin();
1777
1778 /**
1779 * Sometimes we want to conditionally do a transition.
1780 * For example if a client disconnects, we want to go to PRESENT
1781 * only if we weren't already in NOT_PRESENT or ENUMERATING.
1782 */
1783 for (; it != rejectList.end(); ++it) {
1784 if (oldStatus == *it) {
1785 ALOGV("%s: Rejecting status transition for Camera ID %d, "
1786 " since the source state was was in one of the bad "
1787 " states.", __FUNCTION__, cameraId);
1788 mStatusList[cameraId] = oldStatus;
1789 return;
1790 }
1791 }
1792 }
1793
1794 /**
1795 * ProClients lose their exclusive lock.
1796 * - Done before the CameraClient can initialize the HAL device,
1797 * since we want to be able to close it before they get to initialize
1798 */
1799 if (status == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1800 Vector<wp<ProClient> > proClients(mProClientList[cameraId]);
1801 Vector<wp<ProClient> >::const_iterator it;
1802
1803 for (it = proClients.begin(); it != proClients.end(); ++it) {
1804 sp<ProClient> proCl = it->promote();
1805 if (proCl.get() != NULL) {
1806 proCl->onExclusiveLockStolen();
1807 }
1808 }
1809 }
1810
1811 Vector<sp<ICameraServiceListener> >::const_iterator it;
1812 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
1813 (*it)->onStatusChanged(status, cameraId);
1814 }
1815 }
1816 }
1817
getStatus(int cameraId) const1818 ICameraServiceListener::Status CameraService::getStatus(int cameraId) const {
1819 if (cameraId < 0 || cameraId >= MAX_CAMERAS) {
1820 ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId);
1821 return ICameraServiceListener::STATUS_UNKNOWN;
1822 }
1823
1824 Mutex::Autolock al(mStatusMutex);
1825 return mStatusList[cameraId];
1826 }
1827
1828 }; // namespace android
1829