CameraService.h revision 65d14b9825311f9d1847cf282bd0419e71bac666
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 <utils/Vector.h>
21#include <utils/KeyedVector.h>
22#include <binder/AppOpsManager.h>
23#include <binder/BinderService.h>
24#include <binder/IAppOpsCallback.h>
25#include <camera/ICameraService.h>
26#include <hardware/camera.h>
27
28#include <camera/ICamera.h>
29#include <camera/ICameraClient.h>
30#include <camera/IProCameraUser.h>
31#include <camera/IProCameraCallbacks.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
40/* This needs to be increased if we can have more cameras */
41#define MAX_CAMERAS 2
42
43namespace android {
44
45extern volatile int32_t gLogLevel;
46
47class MemoryHeapBase;
48class MediaPlayer;
49
50class CameraService :
51    public BinderService<CameraService>,
52    public BnCameraService,
53    public IBinder::DeathRecipient,
54    public camera_module_callbacks_t
55{
56    friend class BinderService<CameraService>;
57public:
58    class Client;
59    class BasicClient;
60
61    // Implementation of BinderService<T>
62    static char const* getServiceName() { return "media.camera"; }
63
64                        CameraService();
65    virtual             ~CameraService();
66
67    /////////////////////////////////////////////////////////////////////
68    // HAL Callbacks
69    virtual void        onDeviceStatusChanged(int cameraId,
70                                              int newStatus);
71
72    /////////////////////////////////////////////////////////////////////
73    // ICameraService
74    virtual int32_t     getNumberOfCameras();
75    virtual status_t    getCameraInfo(int cameraId,
76                                      struct CameraInfo* cameraInfo);
77    virtual status_t    getCameraCharacteristics(int cameraId,
78                                                 CameraMetadata* cameraInfo);
79    virtual status_t    getCameraVendorTagDescriptor(/*out*/ sp<VendorTagDescriptor>& desc);
80
81    virtual status_t connect(const sp<ICameraClient>& cameraClient, int cameraId,
82            const String16& clientPackageName, int clientUid,
83            /*out*/
84            sp<ICamera>& device);
85
86    virtual status_t connectPro(const sp<IProCameraCallbacks>& cameraCb,
87            int cameraId, const String16& clientPackageName, int clientUid,
88            /*out*/
89            sp<IProCameraUser>& device);
90
91    virtual status_t connectDevice(
92            const sp<ICameraDeviceCallbacks>& cameraCb,
93            int cameraId,
94            const String16& clientPackageName,
95            int clientUid,
96            /*out*/
97            sp<ICameraDeviceUser>& device);
98
99    virtual status_t    addListener(const sp<ICameraServiceListener>& listener);
100    virtual status_t    removeListener(
101                                    const sp<ICameraServiceListener>& listener);
102
103    virtual status_t    getLegacyParameters(
104            int cameraId,
105            /*out*/
106            String16* parameters);
107
108    // OK = supports api of that version, -EOPNOTSUPP = does not support
109    virtual status_t    supportsCameraApi(
110            int cameraId, int apiVersion);
111
112    // Extra permissions checks
113    virtual status_t    onTransact(uint32_t code, const Parcel& data,
114                                   Parcel* reply, uint32_t flags);
115
116    virtual status_t    dump(int fd, const Vector<String16>& args);
117
118    /////////////////////////////////////////////////////////////////////
119    // Client functionality
120    virtual void        removeClientByRemote(const wp<IBinder>& remoteBinder);
121
122    enum sound_kind {
123        SOUND_SHUTTER = 0,
124        SOUND_RECORDING = 1,
125        NUM_SOUNDS
126    };
127
128    void                loadSound();
129    void                playSound(sound_kind kind);
130    void                releaseSound();
131
132    /////////////////////////////////////////////////////////////////////
133    // CameraDeviceFactory functionality
134    int                 getDeviceVersion(int cameraId, int* facing = NULL);
135
136
137    /////////////////////////////////////////////////////////////////////
138    // CameraClient functionality
139
140    // returns plain pointer of client. Note that mClientLock should be acquired to
141    // prevent the client from destruction. The result can be NULL.
142    virtual BasicClient* getClientByIdUnsafe(int cameraId);
143    virtual Mutex*      getClientLockById(int cameraId);
144
145    class BasicClient : public virtual RefBase {
146    public:
147        virtual status_t initialize(camera_module_t *module) = 0;
148
149        virtual void          disconnect() = 0;
150
151        // because we can't virtually inherit IInterface, which breaks
152        // virtual inheritance
153        virtual sp<IBinder> asBinderWrapper() = 0;
154
155        // Return the remote callback binder object (e.g. IProCameraCallbacks)
156        sp<IBinder>     getRemote() {
157            return mRemoteBinder;
158        }
159
160        virtual status_t      dump(int fd, const Vector<String16>& args) = 0;
161
162    protected:
163        BasicClient(const sp<CameraService>& cameraService,
164                const sp<IBinder>& remoteCallback,
165                const String16& clientPackageName,
166                int cameraId,
167                int cameraFacing,
168                int clientPid,
169                uid_t clientUid,
170                int servicePid);
171
172        virtual ~BasicClient();
173
174        // the instance is in the middle of destruction. When this is set,
175        // the instance should not be accessed from callback.
176        // CameraService's mClientLock should be acquired to access this.
177        // - subclasses should set this to true in their destructors.
178        bool                            mDestructionStarted;
179
180        // these are initialized in the constructor.
181        sp<CameraService>               mCameraService;  // immutable after constructor
182        int                             mCameraId;       // immutable after constructor
183        int                             mCameraFacing;   // immutable after constructor
184        const String16                  mClientPackageName;
185        pid_t                           mClientPid;
186        uid_t                           mClientUid;      // immutable after constructor
187        pid_t                           mServicePid;     // immutable after constructor
188
189        // - The app-side Binder interface to receive callbacks from us
190        sp<IBinder>                     mRemoteBinder;   // immutable after constructor
191
192        // permissions management
193        status_t                        startCameraOps();
194        status_t                        finishCameraOps();
195
196        // Notify client about a fatal error
197        virtual void                    notifyError(
198                ICameraDeviceCallbacks::CameraErrorCode errorCode,
199                const CaptureResultExtras& resultExtras) = 0;
200    private:
201        AppOpsManager                   mAppOpsManager;
202
203        class OpsCallback : public BnAppOpsCallback {
204        public:
205            OpsCallback(wp<BasicClient> client);
206            virtual void opChanged(int32_t op, const String16& packageName);
207
208        private:
209            wp<BasicClient> mClient;
210
211        }; // class OpsCallback
212
213        sp<OpsCallback> mOpsCallback;
214        // Track whether startCameraOps was called successfully, to avoid
215        // finishing what we didn't start.
216        bool            mOpsActive;
217
218        // IAppOpsCallback interface, indirected through opListener
219        virtual void opChanged(int32_t op, const String16& packageName);
220    }; // class BasicClient
221
222    class Client : public BnCamera, public BasicClient
223    {
224    public:
225        typedef ICameraClient TCamCallbacks;
226
227        // ICamera interface (see ICamera for details)
228        virtual void          disconnect();
229        virtual status_t      connect(const sp<ICameraClient>& client) = 0;
230        virtual status_t      lock() = 0;
231        virtual status_t      unlock() = 0;
232        virtual status_t      setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
233        virtual void          setPreviewCallbackFlag(int flag) = 0;
234        virtual status_t      setPreviewCallbackTarget(
235                const sp<IGraphicBufferProducer>& callbackProducer) = 0;
236        virtual status_t      startPreview() = 0;
237        virtual void          stopPreview() = 0;
238        virtual bool          previewEnabled() = 0;
239        virtual status_t      storeMetaDataInBuffers(bool enabled) = 0;
240        virtual status_t      startRecording() = 0;
241        virtual void          stopRecording() = 0;
242        virtual bool          recordingEnabled() = 0;
243        virtual void          releaseRecordingFrame(const sp<IMemory>& mem) = 0;
244        virtual status_t      autoFocus() = 0;
245        virtual status_t      cancelAutoFocus() = 0;
246        virtual status_t      takePicture(int msgType) = 0;
247        virtual status_t      setParameters(const String8& params) = 0;
248        virtual String8       getParameters() const = 0;
249        virtual status_t      sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
250
251        // Interface used by CameraService
252        Client(const sp<CameraService>& cameraService,
253                const sp<ICameraClient>& cameraClient,
254                const String16& clientPackageName,
255                int cameraId,
256                int cameraFacing,
257                int clientPid,
258                uid_t clientUid,
259                int servicePid);
260        ~Client();
261
262        // return our camera client
263        const sp<ICameraClient>&    getRemoteCallback() {
264            return mRemoteCallback;
265        }
266
267        virtual sp<IBinder> asBinderWrapper() {
268            return asBinder();
269        }
270
271    protected:
272        static Mutex*        getClientLockFromCookie(void* user);
273        // convert client from cookie. Client lock should be acquired before getting Client.
274        static Client*       getClientFromCookie(void* user);
275
276        virtual void         notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
277                                         const CaptureResultExtras& resultExtras);
278
279        // Initialized in constructor
280
281        // - The app-side Binder interface to receive callbacks from us
282        sp<ICameraClient>               mRemoteCallback;
283
284    }; // class Client
285
286    class ProClient : public BnProCameraUser, public BasicClient {
287    public:
288        typedef IProCameraCallbacks TCamCallbacks;
289
290        ProClient(const sp<CameraService>& cameraService,
291                const sp<IProCameraCallbacks>& remoteCallback,
292                const String16& clientPackageName,
293                int cameraId,
294                int cameraFacing,
295                int clientPid,
296                uid_t clientUid,
297                int servicePid);
298
299        virtual ~ProClient();
300
301        const sp<IProCameraCallbacks>& getRemoteCallback() {
302            return mRemoteCallback;
303        }
304
305        /***
306            IProCamera implementation
307         ***/
308        virtual status_t      connect(const sp<IProCameraCallbacks>& callbacks)
309                                                                            = 0;
310        virtual status_t      exclusiveTryLock() = 0;
311        virtual status_t      exclusiveLock() = 0;
312        virtual status_t      exclusiveUnlock() = 0;
313
314        virtual bool          hasExclusiveLock() = 0;
315
316        // Note that the callee gets a copy of the metadata.
317        virtual int           submitRequest(camera_metadata_t* metadata,
318                                            bool streaming = false) = 0;
319        virtual status_t      cancelRequest(int requestId) = 0;
320
321        // Callbacks from camera service
322        virtual void          onExclusiveLockStolen() = 0;
323
324    protected:
325        virtual void          notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
326                                          const CaptureResultExtras& resultExtras);
327
328        sp<IProCameraCallbacks> mRemoteCallback;
329    }; // class ProClient
330
331private:
332
333    // Delay-load the Camera HAL module
334    virtual void onFirstRef();
335
336    // Step 1. Check if we can connect, before we acquire the service lock.
337    status_t            validateConnect(int cameraId,
338                                        /*inout*/
339                                        int& clientUid) const;
340
341    // Step 2. Check if we can connect, after we acquire the service lock.
342    bool                canConnectUnsafe(int cameraId,
343                                         const String16& clientPackageName,
344                                         const sp<IBinder>& remoteCallback,
345                                         /*out*/
346                                         sp<BasicClient> &client);
347
348    // When connection is successful, initialize client and track its death
349    status_t            connectFinishUnsafe(const sp<BasicClient>& client,
350                                            const sp<IBinder>& remoteCallback);
351
352    virtual sp<BasicClient>  getClientByRemote(const wp<IBinder>& cameraClient);
353
354    Mutex               mServiceLock;
355    // either a Client or CameraDeviceClient
356    wp<BasicClient>     mClient[MAX_CAMERAS];  // protected by mServiceLock
357    Mutex               mClientLock[MAX_CAMERAS]; // prevent Client destruction inside callbacks
358    int                 mNumberOfCameras;
359
360    typedef wp<ProClient> weak_pro_client_ptr;
361    Vector<weak_pro_client_ptr> mProClientList[MAX_CAMERAS];
362
363    // needs to be called with mServiceLock held
364    sp<BasicClient>     findClientUnsafe(const wp<IBinder>& cameraClient, int& outIndex);
365    sp<ProClient>       findProClientUnsafe(
366                                     const wp<IBinder>& cameraCallbacksRemote);
367
368    // atomics to record whether the hardware is allocated to some client.
369    volatile int32_t    mBusy[MAX_CAMERAS];
370    void                setCameraBusy(int cameraId);
371    void                setCameraFree(int cameraId);
372
373    // sounds
374    MediaPlayer*        newMediaPlayer(const char *file);
375
376    Mutex               mSoundLock;
377    sp<MediaPlayer>     mSoundPlayer[NUM_SOUNDS];
378    int                 mSoundRef;  // reference count (release all MediaPlayer when 0)
379
380    camera_module_t *mModule;
381
382    Vector<sp<ICameraServiceListener> >
383                        mListenerList;
384
385    // guard only mStatusList and the broadcasting of ICameraServiceListener
386    mutable Mutex       mStatusMutex;
387    ICameraServiceListener::Status
388                        mStatusList[MAX_CAMERAS];
389
390    // Read the current status (locks mStatusMutex)
391    ICameraServiceListener::Status
392                        getStatus(int cameraId) const;
393
394    typedef Vector<ICameraServiceListener::Status> StatusVector;
395    // Broadcast the new status if it changed (locks the service mutex)
396    void                updateStatus(
397                            ICameraServiceListener::Status status,
398                            int32_t cameraId,
399                            const StatusVector *rejectSourceStates = NULL);
400
401    // IBinder::DeathRecipient implementation
402    virtual void        binderDied(const wp<IBinder> &who);
403
404    // Helpers
405
406    bool                isValidCameraId(int cameraId);
407
408    bool                setUpVendorTags();
409
410    /**
411     * A mapping of camera ids to CameraParameters returned by that camera device.
412     *
413     * This cache is used to generate CameraCharacteristic metadata when using
414     * the HAL1 shim.
415     */
416    KeyedVector<int, CameraParameters>    mShimParams;
417
418    /**
419     * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
420     *
421     * Returns OK on success, or a negative error code.
422     */
423    status_t            initializeShimMetadata(int cameraId);
424
425    /**
426     * Get the cached CameraParameters for the camera. If they haven't been
427     * cached yet, then initialize them for the first time.
428     *
429     * Returns OK on success, or a negative error code.
430     */
431    status_t            getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
432
433    /**
434     * Generate the CameraCharacteristics metadata required by the Camera2 API
435     * from the available HAL1 CameraParameters and CameraInfo.
436     *
437     * Returns OK on success, or a negative error code.
438     */
439    status_t            generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
440
441    /**
442     * Connect a new camera client.  This should only be used while holding the
443     * mutex for mServiceLock.
444     *
445     * Returns OK on success, or a negative error code.
446     */
447    status_t            connectHelperLocked(const sp<ICameraClient>& cameraClient,
448                                      int cameraId,
449                                      const String16& clientPackageName,
450                                      int clientUid,
451                                      int callingPid,
452                                      /*out*/
453                                      sp<Client>& client);
454};
455
456} // namespace android
457
458#endif
459