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