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