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 #ifndef ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
18 #define ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
19
20 #include <cutils/multiuser.h>
21 #include <utils/Vector.h>
22 #include <utils/KeyedVector.h>
23 #include <binder/AppOpsManager.h>
24 #include <binder/BinderService.h>
25 #include <binder/IAppOpsCallback.h>
26 #include <camera/ICameraService.h>
27 #include <camera/ICameraServiceProxy.h>
28 #include <hardware/camera.h>
29
30 #include <camera/ICamera.h>
31 #include <camera/ICameraClient.h>
32 #include <camera/camera2/ICameraDeviceUser.h>
33 #include <camera/camera2/ICameraDeviceCallbacks.h>
34 #include <camera/VendorTagDescriptor.h>
35 #include <camera/CaptureResult.h>
36 #include <camera/CameraParameters.h>
37
38 #include <camera/ICameraServiceListener.h>
39 #include "CameraFlashlight.h"
40
41 #include "common/CameraModule.h"
42 #include "media/RingBuffer.h"
43 #include "utils/AutoConditionLock.h"
44 #include "utils/ClientManager.h"
45
46 #include <set>
47 #include <string>
48 #include <map>
49 #include <memory>
50 #include <utility>
51
52 namespace android {
53
54 extern volatile int32_t gLogLevel;
55
56 class MemoryHeapBase;
57 class MediaPlayer;
58
59 class CameraService :
60 public BinderService<CameraService>,
61 public BnCameraService,
62 public IBinder::DeathRecipient,
63 public camera_module_callbacks_t
64 {
65 friend class BinderService<CameraService>;
66 public:
67 class Client;
68 class BasicClient;
69
70 // The effective API level. The Camera2 API running in LEGACY mode counts as API_1.
71 enum apiLevel {
72 API_1 = 1,
73 API_2 = 2
74 };
75
76 // Process state (mirrors frameworks/base/core/java/android/app/ActivityManager.java)
77 static const int PROCESS_STATE_NONEXISTENT = -1;
78 static const int PROCESS_STATE_TOP = 2;
79 static const int PROCESS_STATE_TOP_SLEEPING = 5;
80
81 // 3 second busy timeout when other clients are connecting
82 static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
83
84 // 1 second busy timeout when other clients are disconnecting
85 static const nsecs_t DEFAULT_DISCONNECT_TIMEOUT_NS = 1000000000;
86
87 // Default number of messages to store in eviction log
88 static const size_t DEFAULT_EVENT_LOG_LENGTH = 100;
89
90 // Event log ID
91 static const int SN_EVENT_LOG_ID = 0x534e4554;
92
93 // Implementation of BinderService<T>
getServiceName()94 static char const* getServiceName() { return "media.camera"; }
95
96 CameraService();
97 virtual ~CameraService();
98
99 /////////////////////////////////////////////////////////////////////
100 // HAL Callbacks
101 virtual void onDeviceStatusChanged(camera_device_status_t cameraId,
102 camera_device_status_t newStatus);
103 virtual void onTorchStatusChanged(const String8& cameraId,
104 ICameraServiceListener::TorchStatus
105 newStatus);
106
107 /////////////////////////////////////////////////////////////////////
108 // ICameraService
109 virtual int32_t getNumberOfCameras(int type);
110 virtual int32_t getNumberOfCameras();
111
112 virtual status_t getCameraInfo(int cameraId,
113 struct CameraInfo* cameraInfo);
114 virtual status_t getCameraCharacteristics(int cameraId,
115 CameraMetadata* cameraInfo);
116 virtual status_t getCameraVendorTagDescriptor(/*out*/ sp<VendorTagDescriptor>& desc);
117
118 virtual status_t connect(const sp<ICameraClient>& cameraClient, int cameraId,
119 const String16& clientPackageName, int clientUid,
120 /*out*/
121 sp<ICamera>& device);
122
123 virtual status_t connectLegacy(const sp<ICameraClient>& cameraClient, int cameraId,
124 int halVersion, const String16& clientPackageName, int clientUid,
125 /*out*/
126 sp<ICamera>& device);
127
128 virtual status_t connectDevice(
129 const sp<ICameraDeviceCallbacks>& cameraCb,
130 int cameraId,
131 const String16& clientPackageName,
132 int clientUid,
133 /*out*/
134 sp<ICameraDeviceUser>& device);
135
136 virtual status_t addListener(const sp<ICameraServiceListener>& listener);
137 virtual status_t removeListener(
138 const sp<ICameraServiceListener>& listener);
139
140 virtual status_t getLegacyParameters(
141 int cameraId,
142 /*out*/
143 String16* parameters);
144
145 virtual status_t setTorchMode(const String16& cameraId, bool enabled,
146 const sp<IBinder>& clientBinder);
147
148 virtual void notifySystemEvent(int32_t eventId, const int32_t* args, size_t length);
149
150 // OK = supports api of that version, -EOPNOTSUPP = does not support
151 virtual status_t supportsCameraApi(
152 int cameraId, int apiVersion);
153
154 // Extra permissions checks
155 virtual status_t onTransact(uint32_t code, const Parcel& data,
156 Parcel* reply, uint32_t flags);
157
158 virtual status_t dump(int fd, const Vector<String16>& args);
159
160 /////////////////////////////////////////////////////////////////////
161 // Client functionality
162
163 enum sound_kind {
164 SOUND_SHUTTER = 0,
165 SOUND_RECORDING_START = 1,
166 SOUND_RECORDING_STOP = 2,
167 NUM_SOUNDS
168 };
169
170 void loadSound();
171 void playSound(sound_kind kind);
172 void releaseSound();
173
174 /**
175 * Update the state of a given camera device (open/close/active/idle) with
176 * the camera proxy service in the system service
177 */
178 static void updateProxyDeviceState(
179 ICameraServiceProxy::CameraState newState,
180 const String8& cameraId);
181
182 /////////////////////////////////////////////////////////////////////
183 // CameraDeviceFactory functionality
184 int getDeviceVersion(int cameraId, int* facing = NULL);
185
186 /////////////////////////////////////////////////////////////////////
187 // Shared utilities
188 static status_t filterGetInfoErrorCode(status_t err);
189
190 /////////////////////////////////////////////////////////////////////
191 // CameraClient functionality
192
193 class BasicClient : public virtual RefBase {
194 public:
195 virtual status_t initialize(CameraModule *module) = 0;
196 virtual void disconnect();
197
198 // because we can't virtually inherit IInterface, which breaks
199 // virtual inheritance
200 virtual sp<IBinder> asBinderWrapper() = 0;
201
202 // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
getRemote()203 sp<IBinder> getRemote() {
204 return mRemoteBinder;
205 }
206
207 // Disallows dumping over binder interface
208 virtual status_t dump(int fd, const Vector<String16>& args);
209 // Internal dump method to be called by CameraService
210 virtual status_t dumpClient(int fd, const Vector<String16>& args) = 0;
211
212 // Return the package name for this client
213 virtual String16 getPackageName() const;
214
215 // Notify client about a fatal error
216 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
217 const CaptureResultExtras& resultExtras) = 0;
218
219 // Get the UID of the application client using this
220 virtual uid_t getClientUid() const;
221
222 // Get the PID of the application client using this
223 virtual int getClientPid() const;
224
225 // Check what API level is used for this client. This is used to determine which
226 // superclass this can be cast to.
227 virtual bool canCastToApiClient(apiLevel level) const;
228 protected:
229 BasicClient(const sp<CameraService>& cameraService,
230 const sp<IBinder>& remoteCallback,
231 const String16& clientPackageName,
232 int cameraId,
233 int cameraFacing,
234 int clientPid,
235 uid_t clientUid,
236 int servicePid);
237
238 virtual ~BasicClient();
239
240 // the instance is in the middle of destruction. When this is set,
241 // the instance should not be accessed from callback.
242 // CameraService's mClientLock should be acquired to access this.
243 // - subclasses should set this to true in their destructors.
244 bool mDestructionStarted;
245
246 // these are initialized in the constructor.
247 sp<CameraService> mCameraService; // immutable after constructor
248 int mCameraId; // immutable after constructor
249 int mCameraFacing; // immutable after constructor
250 const String16 mClientPackageName;
251 pid_t mClientPid;
252 uid_t mClientUid; // immutable after constructor
253 pid_t mServicePid; // immutable after constructor
254 bool mDisconnected;
255
256 // - The app-side Binder interface to receive callbacks from us
257 sp<IBinder> mRemoteBinder; // immutable after constructor
258
259 // permissions management
260 status_t startCameraOps();
261 status_t finishCameraOps();
262
263 private:
264 AppOpsManager mAppOpsManager;
265
266 class OpsCallback : public BnAppOpsCallback {
267 public:
268 OpsCallback(wp<BasicClient> client);
269 virtual void opChanged(int32_t op, const String16& packageName);
270
271 private:
272 wp<BasicClient> mClient;
273
274 }; // class OpsCallback
275
276 sp<OpsCallback> mOpsCallback;
277 // Track whether startCameraOps was called successfully, to avoid
278 // finishing what we didn't start.
279 bool mOpsActive;
280
281 // IAppOpsCallback interface, indirected through opListener
282 virtual void opChanged(int32_t op, const String16& packageName);
283 }; // class BasicClient
284
285 class Client : public BnCamera, public BasicClient
286 {
287 public:
288 typedef ICameraClient TCamCallbacks;
289
290 // ICamera interface (see ICamera for details)
291 virtual void disconnect();
292 virtual status_t connect(const sp<ICameraClient>& client) = 0;
293 virtual status_t lock() = 0;
294 virtual status_t unlock() = 0;
295 virtual status_t setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
296 virtual void setPreviewCallbackFlag(int flag) = 0;
297 virtual status_t setPreviewCallbackTarget(
298 const sp<IGraphicBufferProducer>& callbackProducer) = 0;
299 virtual status_t startPreview() = 0;
300 virtual void stopPreview() = 0;
301 virtual bool previewEnabled() = 0;
302 virtual status_t storeMetaDataInBuffers(bool enabled) = 0;
303 virtual status_t startRecording() = 0;
304 virtual void stopRecording() = 0;
305 virtual bool recordingEnabled() = 0;
306 virtual void releaseRecordingFrame(const sp<IMemory>& mem) = 0;
307 virtual status_t autoFocus() = 0;
308 virtual status_t cancelAutoFocus() = 0;
309 virtual status_t takePicture(int msgType) = 0;
310 virtual status_t setParameters(const String8& params) = 0;
311 virtual String8 getParameters() const = 0;
312 virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
313
314 // Interface used by CameraService
315 Client(const sp<CameraService>& cameraService,
316 const sp<ICameraClient>& cameraClient,
317 const String16& clientPackageName,
318 int cameraId,
319 int cameraFacing,
320 int clientPid,
321 uid_t clientUid,
322 int servicePid);
323 ~Client();
324
325 // return our camera client
getRemoteCallback()326 const sp<ICameraClient>& getRemoteCallback() {
327 return mRemoteCallback;
328 }
329
asBinderWrapper()330 virtual sp<IBinder> asBinderWrapper() {
331 return asBinder(this);
332 }
333
334 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
335 const CaptureResultExtras& resultExtras);
336
337 // Check what API level is used for this client. This is used to determine which
338 // superclass this can be cast to.
339 virtual bool canCastToApiClient(apiLevel level) const;
340 protected:
341 // Convert client from cookie.
342 static sp<CameraService::Client> getClientFromCookie(void* user);
343
344 // Initialized in constructor
345
346 // - The app-side Binder interface to receive callbacks from us
347 sp<ICameraClient> mRemoteCallback;
348
349 }; // class Client
350
351 /**
352 * A listener class that implements the LISTENER interface for use with a ClientManager, and
353 * implements the following methods:
354 * void onClientRemoved(const ClientDescriptor<KEY, VALUE>& descriptor);
355 * void onClientAdded(const ClientDescriptor<KEY, VALUE>& descriptor);
356 */
357 class ClientEventListener {
358 public:
359 void onClientAdded(const resource_policy::ClientDescriptor<String8,
360 sp<CameraService::BasicClient>>& descriptor);
361 void onClientRemoved(const resource_policy::ClientDescriptor<String8,
362 sp<CameraService::BasicClient>>& descriptor);
363 }; // class ClientEventListener
364
365 typedef std::shared_ptr<resource_policy::ClientDescriptor<String8,
366 sp<CameraService::BasicClient>>> DescriptorPtr;
367
368 /**
369 * A container class for managing active camera clients that are using HAL devices. Active
370 * clients are represented by ClientDescriptor objects that contain strong pointers to the
371 * actual BasicClient subclass binder interface implementation.
372 *
373 * This class manages the eviction behavior for the camera clients. See the parent class
374 * implementation in utils/ClientManager for the specifics of this behavior.
375 */
376 class CameraClientManager : public resource_policy::ClientManager<String8,
377 sp<CameraService::BasicClient>, ClientEventListener> {
378 public:
379 CameraClientManager();
380 virtual ~CameraClientManager();
381
382 /**
383 * Return a strong pointer to the active BasicClient for this camera ID, or an empty
384 * if none exists.
385 */
386 sp<CameraService::BasicClient> getCameraClient(const String8& id) const;
387
388 /**
389 * Return a string describing the current state.
390 */
391 String8 toString() const;
392
393 /**
394 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
395 */
396 static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value,
397 int32_t cost, const std::set<String8>& conflictingKeys, int32_t priority,
398 int32_t ownerId);
399
400 /**
401 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
402 * values intialized from a prior ClientDescriptor.
403 */
404 static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
405 const CameraService::DescriptorPtr& partial);
406
407 }; // class CameraClientManager
408
409 private:
410
411 /**
412 * Container class for the state of each logical camera device, including: ID, status, and
413 * dependencies on other devices. The mapping of camera ID -> state saved in mCameraStates
414 * represents the camera devices advertised by the HAL (and any USB devices, when we add
415 * those).
416 *
417 * This container does NOT represent an active camera client. These are represented using
418 * the ClientDescriptors stored in mActiveClientManager.
419 */
420 class CameraState {
421 public:
422 /**
423 * Make a new CameraState and set the ID, cost, and conflicting devices using the values
424 * returned in the HAL's camera_info struct for each device.
425 */
426 CameraState(const String8& id, int cost, const std::set<String8>& conflicting);
427 virtual ~CameraState();
428
429 /**
430 * Return the status for this device.
431 *
432 * This method acquires mStatusLock.
433 */
434 ICameraServiceListener::Status getStatus() const;
435
436 /**
437 * This function updates the status for this camera device, unless the given status
438 * is in the given list of rejected status states, and execute the function passed in
439 * with a signature onStatusUpdateLocked(const String8&, ICameraServiceListener::Status)
440 * if the status has changed.
441 *
442 * This method is idempotent, and will not result in the function passed to
443 * onStatusUpdateLocked being called more than once for the same arguments.
444 * This method aquires mStatusLock.
445 */
446 template<class Func>
447 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
448 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
449 Func onStatusUpdatedLocked);
450
451 /**
452 * Return the last set CameraParameters object generated from the information returned by
453 * the HAL for this device (or an empty CameraParameters object if none has been set).
454 */
455 CameraParameters getShimParams() const;
456
457 /**
458 * Set the CameraParameters for this device.
459 */
460 void setShimParams(const CameraParameters& params);
461
462 /**
463 * Return the resource_cost advertised by the HAL for this device.
464 */
465 int getCost() const;
466
467 /**
468 * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
469 */
470 std::set<String8> getConflicting() const;
471
472 /**
473 * Return the ID of this camera device.
474 */
475 String8 getId() const;
476
477 private:
478 const String8 mId;
479 ICameraServiceListener::Status mStatus; // protected by mStatusLock
480 const int mCost;
481 std::set<String8> mConflicting;
482 mutable Mutex mStatusLock;
483 CameraParameters mShimParams;
484 }; // class CameraState
485
486 // Delay-load the Camera HAL module
487 virtual void onFirstRef();
488
489 // Check if we can connect, before we acquire the service lock.
490 status_t validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid) const;
491
492 // Handle active client evictions, and update service state.
493 // Only call with with mServiceLock held.
494 status_t handleEvictionsLocked(const String8& cameraId, int clientPid,
495 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
496 /*out*/
497 sp<BasicClient>* client,
498 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial);
499
500 // Single implementation shared between the various connect calls
501 template<class CALLBACK, class CLIENT>
502 status_t connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, int halVersion,
503 const String16& clientPackageName, int clientUid, apiLevel effectiveApiLevel,
504 bool legacyMode, bool shimUpdateOnly, /*out*/sp<CLIENT>& device);
505
506 // Lock guarding camera service state
507 Mutex mServiceLock;
508
509 // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
510 std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
511
512 // Return NO_ERROR if the device with a give ID can be connected to
513 status_t checkIfDeviceIsUsable(const String8& cameraId) const;
514
515 // Container for managing currently active application-layer clients
516 CameraClientManager mActiveClientManager;
517
518 // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
519 std::map<String8, std::shared_ptr<CameraState>> mCameraStates;
520
521 // Mutex guarding mCameraStates map
522 mutable Mutex mCameraStatesLock;
523
524 // Circular buffer for storing event logging for dumps
525 RingBuffer<String8> mEventLog;
526 Mutex mLogLock;
527
528 // Currently allowed user IDs
529 std::set<userid_t> mAllowedUsers;
530
531 /**
532 * Check camera capabilities, such as support for basic color operation
533 */
534 int checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId);
535
536 /**
537 * Get the camera state for a given camera id.
538 *
539 * This acquires mCameraStatesLock.
540 */
541 std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const;
542
543 /**
544 * Evict client who's remote binder has died. Returns true if this client was in the active
545 * list and was disconnected.
546 *
547 * This method acquires mServiceLock.
548 */
549 bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
550
551 /**
552 * Remove the given client from the active clients list; does not disconnect the client.
553 *
554 * This method acquires mServiceLock.
555 */
556 void removeByClient(const BasicClient* client);
557
558 /**
559 * Add new client to active clients list after conflicting clients have disconnected using the
560 * values set in the partial descriptor passed in to construct the actual client descriptor.
561 * This is typically called at the end of a connect call.
562 *
563 * This method must be called with mServiceLock held.
564 */
565 void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc);
566
567 /**
568 * Returns the integer corresponding to the given camera ID string, or -1 on failure.
569 */
570 static int cameraIdToInt(const String8& cameraId);
571
572 /**
573 * Remove a single client corresponding to the given camera id from the list of active clients.
574 * If none exists, return an empty strongpointer.
575 *
576 * This method must be called with mServiceLock held.
577 */
578 sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId);
579
580 /**
581 * Handle a notification that the current device user has changed.
582 */
583 void doUserSwitch(const int32_t* newUserId, size_t length);
584
585 /**
586 * Add an event log message.
587 */
588 void logEvent(const char* event);
589
590 /**
591 * Add an event log message that a client has been disconnected.
592 */
593 void logDisconnected(const char* cameraId, int clientPid, const char* clientPackage);
594
595 /**
596 * Add an event log message that a client has been connected.
597 */
598 void logConnected(const char* cameraId, int clientPid, const char* clientPackage);
599
600 /**
601 * Add an event log message that a client's connect attempt has been rejected.
602 */
603 void logRejected(const char* cameraId, int clientPid, const char* clientPackage,
604 const char* reason);
605
606 /**
607 * Add an event log message that the current device user has been switched.
608 */
609 void logUserSwitch(const std::set<userid_t>& oldUserIds,
610 const std::set<userid_t>& newUserIds);
611
612 /**
613 * Add an event log message that a device has been removed by the HAL
614 */
615 void logDeviceRemoved(const char* cameraId, const char* reason);
616
617 /**
618 * Add an event log message that a device has been added by the HAL
619 */
620 void logDeviceAdded(const char* cameraId, const char* reason);
621
622 /**
623 * Add an event log message that a client has unexpectedly died.
624 */
625 void logClientDied(int clientPid, const char* reason);
626
627 /**
628 * Add a event log message that a serious service-level error has occured
629 */
630 void logServiceError(const char* msg, int errorCode);
631
632 /**
633 * Dump the event log to an FD
634 */
635 void dumpEventLog(int fd);
636
637 int mNumberOfCameras;
638 int mNumberOfNormalCameras;
639
640 // sounds
641 MediaPlayer* newMediaPlayer(const char *file);
642
643 Mutex mSoundLock;
644 sp<MediaPlayer> mSoundPlayer[NUM_SOUNDS];
645 int mSoundRef; // reference count (release all MediaPlayer when 0)
646
647 CameraModule* mModule;
648
649 // Guarded by mStatusListenerMutex
650 std::vector<sp<ICameraServiceListener>> mListenerList;
651 Mutex mStatusListenerLock;
652
653 /**
654 * Update the status for the given camera id (if that device exists), and broadcast the
655 * status update to all current ICameraServiceListeners if the status has changed. Any
656 * statuses in rejectedSourceStates will be ignored.
657 *
658 * This method must be idempotent.
659 * This method acquires mStatusLock and mStatusListenerLock.
660 */
661 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
662 std::initializer_list<ICameraServiceListener::Status> rejectedSourceStates);
663 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId);
664
665 // flashlight control
666 sp<CameraFlashlight> mFlashlight;
667 // guard mTorchStatusMap
668 Mutex mTorchStatusMutex;
669 // guard mTorchClientMap
670 Mutex mTorchClientMapMutex;
671 // guard mTorchUidMap
672 Mutex mTorchUidMapMutex;
673 // camera id -> torch status
674 KeyedVector<String8, ICameraServiceListener::TorchStatus> mTorchStatusMap;
675 // camera id -> torch client binder
676 // only store the last client that turns on each camera's torch mode
677 KeyedVector<String8, sp<IBinder>> mTorchClientMap;
678 // camera id -> [incoming uid, current uid] pair
679 std::map<String8, std::pair<int, int>> mTorchUidMap;
680
681 // check and handle if torch client's process has died
682 void handleTorchClientBinderDied(const wp<IBinder> &who);
683
684 // handle torch mode status change and invoke callbacks. mTorchStatusMutex
685 // should be locked.
686 void onTorchStatusChangedLocked(const String8& cameraId,
687 ICameraServiceListener::TorchStatus newStatus);
688
689 // get a camera's torch status. mTorchStatusMutex should be locked.
690 status_t getTorchStatusLocked(const String8 &cameraId,
691 ICameraServiceListener::TorchStatus *status) const;
692
693 // set a camera's torch status. mTorchStatusMutex should be locked.
694 status_t setTorchStatusLocked(const String8 &cameraId,
695 ICameraServiceListener::TorchStatus status);
696
697 // IBinder::DeathRecipient implementation
698 virtual void binderDied(const wp<IBinder> &who);
699
700 // Helpers
701
702 bool setUpVendorTags();
703
704 /**
705 * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
706 *
707 * Returns OK on success, or a negative error code.
708 */
709 status_t initializeShimMetadata(int cameraId);
710
711 /**
712 * Get the cached CameraParameters for the camera. If they haven't been
713 * cached yet, then initialize them for the first time.
714 *
715 * Returns OK on success, or a negative error code.
716 */
717 status_t getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
718
719 /**
720 * Generate the CameraCharacteristics metadata required by the Camera2 API
721 * from the available HAL1 CameraParameters and CameraInfo.
722 *
723 * Returns OK on success, or a negative error code.
724 */
725 status_t generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
726
727 static int getCallingPid();
728
729 static int getCallingUid();
730
731 /**
732 * Get the current system time as a formatted string.
733 */
734 static String8 getFormattedCurrentTime();
735
736 /**
737 * Get the camera eviction priority from the current process state given by ActivityManager.
738 */
739 static int getCameraPriorityFromProcState(int procState);
740
741 static status_t makeClient(const sp<CameraService>& cameraService,
742 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
743 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
744 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
745 /*out*/sp<BasicClient>* client);
746
747 status_t checkCameraAccess(const String16& opPackageName);
748
749 static String8 toString(std::set<userid_t> intSet);
750
751 static sp<ICameraServiceProxy> getCameraServiceProxy();
752 static void pingCameraServiceProxy();
753
754 };
755
756 template<class Func>
updateStatus(ICameraServiceListener::Status status,const String8 & cameraId,std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,Func onStatusUpdatedLocked)757 void CameraService::CameraState::updateStatus(ICameraServiceListener::Status status,
758 const String8& cameraId,
759 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
760 Func onStatusUpdatedLocked) {
761 Mutex::Autolock lock(mStatusLock);
762 ICameraServiceListener::Status oldStatus = mStatus;
763 mStatus = status;
764
765 if (oldStatus == status) {
766 return;
767 }
768
769 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
770 cameraId.string(), oldStatus, status);
771
772 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
773 (status != ICameraServiceListener::STATUS_PRESENT &&
774 status != ICameraServiceListener::STATUS_ENUMERATING)) {
775
776 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
777 __FUNCTION__);
778 mStatus = oldStatus;
779 return;
780 }
781
782 /**
783 * Sometimes we want to conditionally do a transition.
784 * For example if a client disconnects, we want to go to PRESENT
785 * only if we weren't already in NOT_PRESENT or ENUMERATING.
786 */
787 for (auto& rejectStatus : rejectSourceStates) {
788 if (oldStatus == rejectStatus) {
789 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
790 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
791 mStatus = oldStatus;
792 return;
793 }
794 }
795
796 onStatusUpdatedLocked(cameraId, status);
797 }
798
799
800 template<class CALLBACK, class CLIENT>
connectHelper(const sp<CALLBACK> & cameraCb,const String8 & cameraId,int halVersion,const String16 & clientPackageName,int clientUid,apiLevel effectiveApiLevel,bool legacyMode,bool shimUpdateOnly,sp<CLIENT> & device)801 status_t CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
802 int halVersion, const String16& clientPackageName, int clientUid,
803 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
804 /*out*/sp<CLIENT>& device) {
805 status_t ret = NO_ERROR;
806 String8 clientName8(clientPackageName);
807 int clientPid = getCallingPid();
808
809 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
810 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
811 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
812 static_cast<int>(effectiveApiLevel));
813
814 sp<CLIENT> client = nullptr;
815 {
816 // Acquire mServiceLock and prevent other clients from connecting
817 std::unique_ptr<AutoConditionLock> lock =
818 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
819
820 if (lock == nullptr) {
821 ALOGE("CameraService::connect X (PID %d) rejected (too many other clients connecting)."
822 , clientPid);
823 return -EBUSY;
824 }
825
826 // Enforce client permissions and do basic sanity checks
827 if((ret = validateConnectLocked(cameraId, /*inout*/clientUid)) != NO_ERROR) {
828 return ret;
829 }
830
831 // Check the shim parameters after acquiring lock, if they have already been updated and
832 // we were doing a shim update, return immediately
833 if (shimUpdateOnly) {
834 auto cameraState = getCameraState(cameraId);
835 if (cameraState != nullptr) {
836 if (!cameraState->getShimParams().isEmpty()) return NO_ERROR;
837 }
838 }
839
840 sp<BasicClient> clientTmp = nullptr;
841 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
842 if ((ret = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
843 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
844 /*out*/&partial)) != NO_ERROR) {
845 return ret;
846 }
847
848 if (clientTmp.get() != nullptr) {
849 // Handle special case for API1 MediaRecorder where the existing client is returned
850 device = static_cast<CLIENT*>(clientTmp.get());
851 return NO_ERROR;
852 }
853
854 // give flashlight a chance to close devices if necessary.
855 mFlashlight->prepareDeviceOpen(cameraId);
856
857 // TODO: Update getDeviceVersion + HAL interface to use strings for Camera IDs
858 int id = cameraIdToInt(cameraId);
859 if (id == -1) {
860 ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
861 cameraId.string());
862 return BAD_VALUE;
863 }
864
865 int facing = -1;
866 int deviceVersion = getDeviceVersion(id, /*out*/&facing);
867 sp<BasicClient> tmp = nullptr;
868 if((ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
869 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
870 /*out*/&tmp)) != NO_ERROR) {
871 return ret;
872 }
873 client = static_cast<CLIENT*>(tmp.get());
874
875 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
876 __FUNCTION__);
877
878 if ((ret = client->initialize(mModule)) != OK) {
879 ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
880 return ret;
881 }
882
883 // Update shim paremeters for legacy clients
884 if (effectiveApiLevel == API_1) {
885 // Assume we have always received a Client subclass for API1
886 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
887 String8 rawParams = shimClient->getParameters();
888 CameraParameters params(rawParams);
889
890 auto cameraState = getCameraState(cameraId);
891 if (cameraState != nullptr) {
892 cameraState->setShimParams(params);
893 } else {
894 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
895 __FUNCTION__, cameraId.string());
896 }
897 }
898
899 if (shimUpdateOnly) {
900 // If only updating legacy shim parameters, immediately disconnect client
901 mServiceLock.unlock();
902 client->disconnect();
903 mServiceLock.lock();
904 } else {
905 // Otherwise, add client to active clients list
906 finishConnectLocked(client, partial);
907 }
908 } // lock is destroyed, allow further connect calls
909
910 // Important: release the mutex here so the client can call back into the service from its
911 // destructor (can be at the end of the call)
912 device = client;
913 return NO_ERROR;
914 }
915
916 } // namespace android
917
918 #endif
919