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