• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <android/hardware/BnCameraService.h>
21 #include <android/hardware/ICameraServiceListener.h>
22 
23 #include <cutils/multiuser.h>
24 #include <utils/Vector.h>
25 #include <utils/KeyedVector.h>
26 #include <binder/AppOpsManager.h>
27 #include <binder/BinderService.h>
28 #include <binder/IAppOpsCallback.h>
29 #include <camera/ICameraServiceProxy.h>
30 #include <hardware/camera.h>
31 
32 #include <camera/VendorTagDescriptor.h>
33 #include <camera/CaptureResult.h>
34 #include <camera/CameraParameters.h>
35 
36 #include "CameraFlashlight.h"
37 
38 #include "common/CameraModule.h"
39 #include "media/RingBuffer.h"
40 #include "utils/AutoConditionLock.h"
41 #include "utils/ClientManager.h"
42 
43 #include <set>
44 #include <string>
45 #include <map>
46 #include <memory>
47 #include <utility>
48 
49 namespace android {
50 
51 extern volatile int32_t gLogLevel;
52 
53 class MemoryHeapBase;
54 class MediaPlayer;
55 
56 class CameraService :
57     public BinderService<CameraService>,
58     public ::android::hardware::BnCameraService,
59     public IBinder::DeathRecipient,
60     public camera_module_callbacks_t
61 {
62     friend class BinderService<CameraService>;
63 public:
64     class Client;
65     class BasicClient;
66 
67     // The effective API level.  The Camera2 API running in LEGACY mode counts as API_1.
68     enum apiLevel {
69         API_1 = 1,
70         API_2 = 2
71     };
72 
73     // Process state (mirrors frameworks/base/core/java/android/app/ActivityManager.java)
74     static const int PROCESS_STATE_NONEXISTENT = -1;
75     static const int PROCESS_STATE_TOP = 2;
76     static const int PROCESS_STATE_TOP_SLEEPING = 5;
77 
78     // 3 second busy timeout when other clients are connecting
79     static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
80 
81     // 1 second busy timeout when other clients are disconnecting
82     static const nsecs_t DEFAULT_DISCONNECT_TIMEOUT_NS = 1000000000;
83 
84     // Default number of messages to store in eviction log
85     static const size_t DEFAULT_EVENT_LOG_LENGTH = 100;
86 
87     // Event log ID
88     static const int SN_EVENT_LOG_ID = 0x534e4554;
89 
90     // Implementation of BinderService<T>
getServiceName()91     static char const* getServiceName() { return "media.camera"; }
92 
93                         CameraService();
94     virtual             ~CameraService();
95 
96     /////////////////////////////////////////////////////////////////////
97     // HAL Callbacks
98     virtual void        onDeviceStatusChanged(camera_device_status_t cameraId,
99                                               camera_device_status_t newStatus);
100     virtual void        onTorchStatusChanged(const String8& cameraId,
101                                              int32_t newStatus);
102 
103     /////////////////////////////////////////////////////////////////////
104     // ICameraService
105     virtual binder::Status     getNumberOfCameras(int32_t type, int32_t* numCameras);
106 
107     virtual binder::Status     getCameraInfo(int cameraId,
108             hardware::CameraInfo* cameraInfo);
109     virtual binder::Status     getCameraCharacteristics(int cameraId,
110             CameraMetadata* cameraInfo);
111     virtual binder::Status     getCameraVendorTagDescriptor(
112             /*out*/
113             hardware::camera2::params::VendorTagDescriptor* desc);
114 
115     virtual binder::Status     connect(const sp<hardware::ICameraClient>& cameraClient,
116             int32_t cameraId, const String16& clientPackageName,
117             int32_t clientUid, int clientPid,
118             /*out*/
119             sp<hardware::ICamera>* device);
120 
121     virtual binder::Status     connectLegacy(const sp<hardware::ICameraClient>& cameraClient,
122             int32_t cameraId, int32_t halVersion,
123             const String16& clientPackageName, int32_t clientUid,
124             /*out*/
125             sp<hardware::ICamera>* device);
126 
127     virtual binder::Status     connectDevice(
128             const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb, int32_t cameraId,
129             const String16& clientPackageName, int32_t clientUid,
130             /*out*/
131             sp<hardware::camera2::ICameraDeviceUser>* device);
132 
133     virtual binder::Status    addListener(const sp<hardware::ICameraServiceListener>& listener);
134     virtual binder::Status    removeListener(
135             const sp<hardware::ICameraServiceListener>& listener);
136 
137     virtual binder::Status    getLegacyParameters(
138             int32_t cameraId,
139             /*out*/
140             String16* parameters);
141 
142     virtual binder::Status    setTorchMode(const String16& cameraId, bool enabled,
143             const sp<IBinder>& clientBinder);
144 
145     virtual binder::Status    notifySystemEvent(int32_t eventId,
146             const std::vector<int32_t>& args);
147 
148     // OK = supports api of that version, -EOPNOTSUPP = does not support
149     virtual binder::Status    supportsCameraApi(
150             int32_t cameraId, int32_t apiVersion,
151             /*out*/
152             bool *isSupported);
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 binder::Status 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 binder::Status 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(int32_t 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         String16                        mClientPackageName; // immutable after constructor
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 hardware::BnCamera, public BasicClient
286     {
287     public:
288         typedef hardware::ICameraClient TCamCallbacks;
289 
290         // ICamera interface (see ICamera for details)
291         virtual binder::Status disconnect();
292         virtual status_t      connect(const sp<hardware::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      setVideoBufferMode(int32_t videoBufferMode) = 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         virtual status_t      setVideoTarget(const sp<IGraphicBufferProducer>& bufferProducer) = 0;
314 
315         // Interface used by CameraService
316         Client(const sp<CameraService>& cameraService,
317                 const sp<hardware::ICameraClient>& cameraClient,
318                 const String16& clientPackageName,
319                 int cameraId,
320                 int cameraFacing,
321                 int clientPid,
322                 uid_t clientUid,
323                 int servicePid);
324         ~Client();
325 
326         // return our camera client
getRemoteCallback()327         const sp<hardware::ICameraClient>&    getRemoteCallback() {
328             return mRemoteCallback;
329         }
330 
asBinderWrapper()331         virtual sp<IBinder> asBinderWrapper() {
332             return asBinder(this);
333         }
334 
335         virtual void         notifyError(int32_t errorCode,
336                                          const CaptureResultExtras& resultExtras);
337 
338         // Check what API level is used for this client. This is used to determine which
339         // superclass this can be cast to.
340         virtual bool canCastToApiClient(apiLevel level) const;
341     protected:
342         // Convert client from cookie.
343         static sp<CameraService::Client> getClientFromCookie(void* user);
344 
345         // Initialized in constructor
346 
347         // - The app-side Binder interface to receive callbacks from us
348         sp<hardware::ICameraClient>               mRemoteCallback;
349 
350     }; // class Client
351 
352     /**
353      * A listener class that implements the LISTENER interface for use with a ClientManager, and
354      * implements the following methods:
355      *    void onClientRemoved(const ClientDescriptor<KEY, VALUE>& descriptor);
356      *    void onClientAdded(const ClientDescriptor<KEY, VALUE>& descriptor);
357      */
358     class ClientEventListener {
359     public:
360         void onClientAdded(const resource_policy::ClientDescriptor<String8,
361                 sp<CameraService::BasicClient>>& descriptor);
362         void onClientRemoved(const resource_policy::ClientDescriptor<String8,
363                 sp<CameraService::BasicClient>>& descriptor);
364     }; // class ClientEventListener
365 
366     typedef std::shared_ptr<resource_policy::ClientDescriptor<String8,
367             sp<CameraService::BasicClient>>> DescriptorPtr;
368 
369     /**
370      * A container class for managing active camera clients that are using HAL devices.  Active
371      * clients are represented by ClientDescriptor objects that contain strong pointers to the
372      * actual BasicClient subclass binder interface implementation.
373      *
374      * This class manages the eviction behavior for the camera clients.  See the parent class
375      * implementation in utils/ClientManager for the specifics of this behavior.
376      */
377     class CameraClientManager : public resource_policy::ClientManager<String8,
378             sp<CameraService::BasicClient>, ClientEventListener> {
379     public:
380         CameraClientManager();
381         virtual ~CameraClientManager();
382 
383         /**
384          * Return a strong pointer to the active BasicClient for this camera ID, or an empty
385          * if none exists.
386          */
387         sp<CameraService::BasicClient> getCameraClient(const String8& id) const;
388 
389         /**
390          * Return a string describing the current state.
391          */
392         String8 toString() const;
393 
394         /**
395          * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
396          */
397         static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value,
398                 int32_t cost, const std::set<String8>& conflictingKeys, int32_t priority,
399                 int32_t ownerId);
400 
401         /**
402          * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
403          * values intialized from a prior ClientDescriptor.
404          */
405         static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
406                 const CameraService::DescriptorPtr& partial);
407 
408     }; // class CameraClientManager
409 
410 private:
411 
412     /**
413      * Container class for the state of each logical camera device, including: ID, status, and
414      * dependencies on other devices.  The mapping of camera ID -> state saved in mCameraStates
415      * represents the camera devices advertised by the HAL (and any USB devices, when we add
416      * those).
417      *
418      * This container does NOT represent an active camera client.  These are represented using
419      * the ClientDescriptors stored in mActiveClientManager.
420      */
421     class CameraState {
422     public:
423         /**
424          * Make a new CameraState and set the ID, cost, and conflicting devices using the values
425          * returned in the HAL's camera_info struct for each device.
426          */
427         CameraState(const String8& id, int cost, const std::set<String8>& conflicting);
428         virtual ~CameraState();
429 
430         /**
431          * Return the status for this device.
432          *
433          * This method acquires mStatusLock.
434          */
435         int32_t getStatus() const;
436 
437         /**
438          * This function updates the status for this camera device, unless the given status
439          * is in the given list of rejected status states, and execute the function passed in
440          * with a signature onStatusUpdateLocked(const String8&, int32_t)
441          * if the status has changed.
442          *
443          * This method is idempotent, and will not result in the function passed to
444          * onStatusUpdateLocked being called more than once for the same arguments.
445          * This method aquires mStatusLock.
446          */
447         template<class Func>
448         void updateStatus(int32_t status, const String8& cameraId,
449                 std::initializer_list<int32_t> rejectSourceStates,
450                 Func onStatusUpdatedLocked);
451 
452         /**
453          * Return the last set CameraParameters object generated from the information returned by
454          * the HAL for this device (or an empty CameraParameters object if none has been set).
455          */
456         CameraParameters getShimParams() const;
457 
458         /**
459          * Set the CameraParameters for this device.
460          */
461         void setShimParams(const CameraParameters& params);
462 
463         /**
464          * Return the resource_cost advertised by the HAL for this device.
465          */
466         int getCost() const;
467 
468         /**
469          * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
470          */
471         std::set<String8> getConflicting() const;
472 
473         /**
474          * Return the ID of this camera device.
475          */
476         String8 getId() const;
477 
478     private:
479         const String8 mId;
480         int32_t mStatus; // protected by mStatusLock
481         const int mCost;
482         std::set<String8> mConflicting;
483         mutable Mutex mStatusLock;
484         CameraParameters mShimParams;
485     }; // class CameraState
486 
487     // Delay-load the Camera HAL module
488     virtual void onFirstRef();
489 
490     // Check if we can connect, before we acquire the service lock.
491     // The returned originalClientPid is the PID of the original process that wants to connect to
492     // camera.
493     // The returned clientPid is the PID of the client that directly connects to camera.
494     // originalClientPid and clientPid are usually the same except when the application uses
495     // mediaserver to connect to camera (using MediaRecorder to connect to camera). In that case,
496     // clientPid is the PID of mediaserver and originalClientPid is the PID of the application.
497     binder::Status validateConnectLocked(const String8& cameraId, const String8& clientName8,
498           /*inout*/int& clientUid, /*inout*/int& clientPid, /*out*/int& originalClientPid) const;
499 
500     // Handle active client evictions, and update service state.
501     // Only call with with mServiceLock held.
502     status_t handleEvictionsLocked(const String8& cameraId, int clientPid,
503         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
504         /*out*/
505         sp<BasicClient>* client,
506         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial);
507 
508     // Single implementation shared between the various connect calls
509     template<class CALLBACK, class CLIENT>
510     binder::Status connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
511             int halVersion, const String16& clientPackageName,
512             int clientUid, int clientPid,
513             apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
514             /*out*/sp<CLIENT>& device);
515 
516     // Lock guarding camera service state
517     Mutex               mServiceLock;
518 
519     // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
520     std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
521 
522     // Return NO_ERROR if the device with a give ID can be connected to
523     status_t checkIfDeviceIsUsable(const String8& cameraId) const;
524 
525     // Container for managing currently active application-layer clients
526     CameraClientManager mActiveClientManager;
527 
528     // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
529     std::map<String8, std::shared_ptr<CameraState>> mCameraStates;
530 
531     // Mutex guarding mCameraStates map
532     mutable Mutex mCameraStatesLock;
533 
534     // Circular buffer for storing event logging for dumps
535     RingBuffer<String8> mEventLog;
536     Mutex mLogLock;
537 
538     // Currently allowed user IDs
539     std::set<userid_t> mAllowedUsers;
540 
541     /**
542      * Check camera capabilities, such as support for basic color operation
543      */
544     int checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId);
545 
546     /**
547      * Get the camera state for a given camera id.
548      *
549      * This acquires mCameraStatesLock.
550      */
551     std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const;
552 
553     /**
554      * Evict client who's remote binder has died.  Returns true if this client was in the active
555      * list and was disconnected.
556      *
557      * This method acquires mServiceLock.
558      */
559     bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
560 
561     /**
562      * Remove the given client from the active clients list; does not disconnect the client.
563      *
564      * This method acquires mServiceLock.
565      */
566     void removeByClient(const BasicClient* client);
567 
568     /**
569      * Add new client to active clients list after conflicting clients have disconnected using the
570      * values set in the partial descriptor passed in to construct the actual client descriptor.
571      * This is typically called at the end of a connect call.
572      *
573      * This method must be called with mServiceLock held.
574      */
575     void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc);
576 
577     /**
578      * Returns the integer corresponding to the given camera ID string, or -1 on failure.
579      */
580     static int cameraIdToInt(const String8& cameraId);
581 
582     /**
583      * Remove a single client corresponding to the given camera id from the list of active clients.
584      * If none exists, return an empty strongpointer.
585      *
586      * This method must be called with mServiceLock held.
587      */
588     sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId);
589 
590     /**
591      * Handle a notification that the current device user has changed.
592      */
593     void doUserSwitch(const std::vector<int32_t>& newUserIds);
594 
595     /**
596      * Add an event log message.
597      */
598     void logEvent(const char* event);
599 
600     /**
601      * Add an event log message that a client has been disconnected.
602      */
603     void logDisconnected(const char* cameraId, int clientPid, const char* clientPackage);
604 
605     /**
606      * Add an event log message that a client has been connected.
607      */
608     void logConnected(const char* cameraId, int clientPid, const char* clientPackage);
609 
610     /**
611      * Add an event log message that a client's connect attempt has been rejected.
612      */
613     void logRejected(const char* cameraId, int clientPid, const char* clientPackage,
614             const char* reason);
615 
616     /**
617      * Add an event log message that the current device user has been switched.
618      */
619     void logUserSwitch(const std::set<userid_t>& oldUserIds,
620         const std::set<userid_t>& newUserIds);
621 
622     /**
623      * Add an event log message that a device has been removed by the HAL
624      */
625     void logDeviceRemoved(const char* cameraId, const char* reason);
626 
627     /**
628      * Add an event log message that a device has been added by the HAL
629      */
630     void logDeviceAdded(const char* cameraId, const char* reason);
631 
632     /**
633      * Add an event log message that a client has unexpectedly died.
634      */
635     void logClientDied(int clientPid, const char* reason);
636 
637     /**
638      * Add a event log message that a serious service-level error has occured
639      * The errorCode should be one of the Android Errors
640      */
641     void logServiceError(const char* msg, int errorCode);
642 
643     /**
644      * Dump the event log to an FD
645      */
646     void dumpEventLog(int fd);
647 
648     int                 mNumberOfCameras;
649     int                 mNumberOfNormalCameras;
650 
651     // sounds
652     MediaPlayer*        newMediaPlayer(const char *file);
653 
654     Mutex               mSoundLock;
655     sp<MediaPlayer>     mSoundPlayer[NUM_SOUNDS];
656     int                 mSoundRef;  // reference count (release all MediaPlayer when 0)
657 
658     CameraModule*     mModule;
659 
660     // Guarded by mStatusListenerMutex
661     std::vector<sp<hardware::ICameraServiceListener>> mListenerList;
662     Mutex       mStatusListenerLock;
663 
664     /**
665      * Update the status for the given camera id (if that device exists), and broadcast the
666      * status update to all current ICameraServiceListeners if the status has changed.  Any
667      * statuses in rejectedSourceStates will be ignored.
668      *
669      * This method must be idempotent.
670      * This method acquires mStatusLock and mStatusListenerLock.
671      */
672     void updateStatus(int32_t status, const String8& cameraId,
673             std::initializer_list<int32_t> rejectedSourceStates);
674     void updateStatus(int32_t status, const String8& cameraId);
675 
676     // flashlight control
677     sp<CameraFlashlight> mFlashlight;
678     // guard mTorchStatusMap
679     Mutex                mTorchStatusMutex;
680     // guard mTorchClientMap
681     Mutex                mTorchClientMapMutex;
682     // guard mTorchUidMap
683     Mutex                mTorchUidMapMutex;
684     // camera id -> torch status
685     KeyedVector<String8, int32_t> mTorchStatusMap;
686     // camera id -> torch client binder
687     // only store the last client that turns on each camera's torch mode
688     KeyedVector<String8, sp<IBinder>> mTorchClientMap;
689     // camera id -> [incoming uid, current uid] pair
690     std::map<String8, std::pair<int, int>> mTorchUidMap;
691 
692     // check and handle if torch client's process has died
693     void handleTorchClientBinderDied(const wp<IBinder> &who);
694 
695     // handle torch mode status change and invoke callbacks. mTorchStatusMutex
696     // should be locked.
697     void onTorchStatusChangedLocked(const String8& cameraId,
698             int32_t newStatus);
699 
700     // get a camera's torch status. mTorchStatusMutex should be locked.
701     status_t getTorchStatusLocked(const String8 &cameraId,
702             int32_t *status) const;
703 
704     // set a camera's torch status. mTorchStatusMutex should be locked.
705     status_t setTorchStatusLocked(const String8 &cameraId,
706             int32_t status);
707 
708     // IBinder::DeathRecipient implementation
709     virtual void        binderDied(const wp<IBinder> &who);
710 
711     // Helpers
712 
713     bool                setUpVendorTags();
714 
715     /**
716      * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
717      *
718      * Sets Status to a service-specific error on failure
719      */
720     binder::Status      initializeShimMetadata(int cameraId);
721 
722     /**
723      * Get the cached CameraParameters for the camera. If they haven't been
724      * cached yet, then initialize them for the first time.
725      *
726      * Sets Status to a service-specific error on failure
727      */
728     binder::Status      getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
729 
730     /**
731      * Generate the CameraCharacteristics metadata required by the Camera2 API
732      * from the available HAL1 CameraParameters and CameraInfo.
733      *
734      * Sets Status to a service-specific error on failure
735      */
736     binder::Status      generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
737 
738     static int getCallingPid();
739 
740     static int getCallingUid();
741 
742     /**
743      * Get the current system time as a formatted string.
744      */
745     static String8 getFormattedCurrentTime();
746 
747     /**
748      * Get the camera eviction priority from the current process state given by ActivityManager.
749      */
750     static int getCameraPriorityFromProcState(int procState);
751 
752     static binder::Status makeClient(const sp<CameraService>& cameraService,
753             const sp<IInterface>& cameraCb, const String16& packageName, int cameraId,
754             int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
755             int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
756             /*out*/sp<BasicClient>* client);
757 
758     status_t checkCameraAccess(const String16& opPackageName);
759 
760     static String8 toString(std::set<userid_t> intSet);
761 
762     static sp<ICameraServiceProxy> getCameraServiceProxy();
763     static void pingCameraServiceProxy();
764 
765 };
766 
767 template<class Func>
updateStatus(int32_t status,const String8 & cameraId,std::initializer_list<int32_t> rejectSourceStates,Func onStatusUpdatedLocked)768 void CameraService::CameraState::updateStatus(int32_t status,
769         const String8& cameraId,
770         std::initializer_list<int32_t> rejectSourceStates,
771         Func onStatusUpdatedLocked) {
772     Mutex::Autolock lock(mStatusLock);
773     int32_t oldStatus = mStatus;
774     mStatus = status;
775 
776     if (oldStatus == status) {
777         return;
778     }
779 
780     ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
781             cameraId.string(), oldStatus, status);
782 
783     if (oldStatus == hardware::ICameraServiceListener::STATUS_NOT_PRESENT &&
784             (status != hardware::ICameraServiceListener::STATUS_PRESENT &&
785              status != hardware::ICameraServiceListener::STATUS_ENUMERATING)) {
786 
787         ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
788                 __FUNCTION__);
789         mStatus = oldStatus;
790         return;
791     }
792 
793     /**
794      * Sometimes we want to conditionally do a transition.
795      * For example if a client disconnects, we want to go to PRESENT
796      * only if we weren't already in NOT_PRESENT or ENUMERATING.
797      */
798     for (auto& rejectStatus : rejectSourceStates) {
799         if (oldStatus == rejectStatus) {
800             ALOGV("%s: Rejecting status transition for Camera ID %s,  since the source "
801                     "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
802             mStatus = oldStatus;
803             return;
804         }
805     }
806 
807     onStatusUpdatedLocked(cameraId, status);
808 }
809 
810 #define STATUS_ERROR(errorCode, errorString) \
811     binder::Status::fromServiceSpecificError(errorCode, \
812             String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
813 
814 #define STATUS_ERROR_FMT(errorCode, errorString, ...) \
815     binder::Status::fromServiceSpecificError(errorCode, \
816             String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, __VA_ARGS__))
817 
818 
819 template<class CALLBACK, class CLIENT>
connectHelper(const sp<CALLBACK> & cameraCb,const String8 & cameraId,int halVersion,const String16 & clientPackageName,int clientUid,int clientPid,apiLevel effectiveApiLevel,bool legacyMode,bool shimUpdateOnly,sp<CLIENT> & device)820 binder::Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
821         int halVersion, const String16& clientPackageName, int clientUid, int clientPid,
822         apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
823         /*out*/sp<CLIENT>& device) {
824     binder::Status ret = binder::Status::ok();
825 
826     String8 clientName8(clientPackageName);
827 
828     int originalClientPid = 0;
829 
830     ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
831             "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
832             (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
833             static_cast<int>(effectiveApiLevel));
834 
835     sp<CLIENT> client = nullptr;
836     {
837         // Acquire mServiceLock and prevent other clients from connecting
838         std::unique_ptr<AutoConditionLock> lock =
839                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
840 
841         if (lock == nullptr) {
842             ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
843                     , clientPid);
844             return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
845                     "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
846                     cameraId.string(), clientName8.string(), clientPid);
847         }
848 
849         // Enforce client permissions and do basic sanity checks
850         if(!(ret = validateConnectLocked(cameraId, clientName8,
851                 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
852             return ret;
853         }
854 
855         // Check the shim parameters after acquiring lock, if they have already been updated and
856         // we were doing a shim update, return immediately
857         if (shimUpdateOnly) {
858             auto cameraState = getCameraState(cameraId);
859             if (cameraState != nullptr) {
860                 if (!cameraState->getShimParams().isEmpty()) return ret;
861             }
862         }
863 
864         status_t err;
865 
866         sp<BasicClient> clientTmp = nullptr;
867         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
868         if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
869                 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
870                 /*out*/&partial)) != NO_ERROR) {
871             switch (err) {
872                 case -ENODEV:
873                     return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
874                             "No camera device with ID \"%s\" currently available",
875                             cameraId.string());
876                 case -EBUSY:
877                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
878                             "Higher-priority client using camera, ID \"%s\" currently unavailable",
879                             cameraId.string());
880                 default:
881                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
882                             "Unexpected error %s (%d) opening camera \"%s\"",
883                             strerror(-err), err, cameraId.string());
884             }
885         }
886 
887         if (clientTmp.get() != nullptr) {
888             // Handle special case for API1 MediaRecorder where the existing client is returned
889             device = static_cast<CLIENT*>(clientTmp.get());
890             return ret;
891         }
892 
893         // give flashlight a chance to close devices if necessary.
894         mFlashlight->prepareDeviceOpen(cameraId);
895 
896         // TODO: Update getDeviceVersion + HAL interface to use strings for Camera IDs
897         int id = cameraIdToInt(cameraId);
898         if (id == -1) {
899             ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
900                     cameraId.string());
901             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
902                     "Bad camera ID \"%s\" passed to camera open", cameraId.string());
903         }
904 
905         int facing = -1;
906         int deviceVersion = getDeviceVersion(id, /*out*/&facing);
907         sp<BasicClient> tmp = nullptr;
908         if(!(ret = makeClient(this, cameraCb, clientPackageName, id, facing, clientPid,
909                 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
910                 /*out*/&tmp)).isOk()) {
911             return ret;
912         }
913         client = static_cast<CLIENT*>(tmp.get());
914 
915         LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
916                 __FUNCTION__);
917 
918         if ((err = client->initialize(mModule)) != OK) {
919             ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
920             // Errors could be from the HAL module open call or from AppOpsManager
921             switch(err) {
922                 case BAD_VALUE:
923                     return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
924                             "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
925                 case -EBUSY:
926                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
927                             "Camera \"%s\" is already open", cameraId.string());
928                 case -EUSERS:
929                     return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
930                             "Too many cameras already open, cannot open camera \"%s\"",
931                             cameraId.string());
932                 case PERMISSION_DENIED:
933                     return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
934                             "No permission to open camera \"%s\"", cameraId.string());
935                 case -EACCES:
936                     return STATUS_ERROR_FMT(ERROR_DISABLED,
937                             "Camera \"%s\" disabled by policy", cameraId.string());
938                 case -ENODEV:
939                 default:
940                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
941                             "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
942                             strerror(-err), err);
943             }
944         }
945 
946         // Update shim paremeters for legacy clients
947         if (effectiveApiLevel == API_1) {
948             // Assume we have always received a Client subclass for API1
949             sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
950             String8 rawParams = shimClient->getParameters();
951             CameraParameters params(rawParams);
952 
953             auto cameraState = getCameraState(cameraId);
954             if (cameraState != nullptr) {
955                 cameraState->setShimParams(params);
956             } else {
957                 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
958                         __FUNCTION__, cameraId.string());
959             }
960         }
961 
962         if (shimUpdateOnly) {
963             // If only updating legacy shim parameters, immediately disconnect client
964             mServiceLock.unlock();
965             client->disconnect();
966             mServiceLock.lock();
967         } else {
968             // Otherwise, add client to active clients list
969             finishConnectLocked(client, partial);
970         }
971     } // lock is destroyed, allow further connect calls
972 
973     // Important: release the mutex here so the client can call back into the service from its
974     // destructor (can be at the end of the call)
975     device = client;
976     return ret;
977 }
978 
979 #undef STATUS_ERROR_FMT
980 #undef STATUS_ERROR
981 
982 } // namespace android
983 
984 #endif
985