CameraHardwareInterface.h revision 4717c470bf989e02f798857358471f8feb77660f
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_HARDWARE_CAMERA_HARDWARE_INTERFACE_H
18#define ANDROID_HARDWARE_CAMERA_HARDWARE_INTERFACE_H
19
20#include <unordered_map>
21#include <binder/IMemory.h>
22#include <binder/MemoryBase.h>
23#include <binder/MemoryHeapBase.h>
24#include <utils/RefBase.h>
25#include <ui/GraphicBuffer.h>
26#include <camera/Camera.h>
27#include <camera/CameraParameters.h>
28#include <system/window.h>
29#include <hardware/camera.h>
30
31#include <common/CameraModule.h>
32#include <common/CameraProviderManager.h>
33
34namespace android {
35
36typedef void (*notify_callback)(int32_t msgType,
37                            int32_t ext1,
38                            int32_t ext2,
39                            void* user);
40
41typedef void (*data_callback)(int32_t msgType,
42                            const sp<IMemory> &dataPtr,
43                            camera_frame_metadata_t *metadata,
44                            void* user);
45
46typedef void (*data_callback_timestamp)(nsecs_t timestamp,
47                            int32_t msgType,
48                            const sp<IMemory> &dataPtr,
49                            void *user);
50
51/**
52 * CameraHardwareInterface.h defines the interface to the
53 * camera hardware abstraction layer, used for setting and getting
54 * parameters, live previewing, and taking pictures. It is used for
55 * HAL devices with version CAMERA_DEVICE_API_VERSION_1_0 only.
56 *
57 * It is a referenced counted interface with RefBase as its base class.
58 * CameraService calls openCameraHardware() to retrieve a strong pointer to the
59 * instance of this interface and may be called multiple times. The
60 * following steps describe a typical sequence:
61 *
62 *   -# After CameraService calls openCameraHardware(), getParameters() and
63 *      setParameters() are used to initialize the camera instance.
64 *   -# startPreview() is called.
65 *
66 * Prior to taking a picture, CameraService often calls autofocus(). When auto
67 * focusing has completed, the camera instance sends a CAMERA_MSG_FOCUS notification,
68 * which informs the application whether focusing was successful. The camera instance
69 * only sends this message once and it is up  to the application to call autoFocus()
70 * again if refocusing is desired.
71 *
72 * CameraService calls takePicture() to request the camera instance take a
73 * picture. At this point, if a shutter, postview, raw, and/or compressed
74 * callback is desired, the corresponding message must be enabled. Any memory
75 * provided in a data callback must be copied if it's needed after returning.
76 */
77
78class CameraHardwareInterface :
79        public virtual RefBase,
80        public virtual hardware::camera::device::V1_0::ICameraDeviceCallback,
81        public virtual hardware::camera::device::V1_0::ICameraDevicePreviewCallback {
82
83public:
84    explicit CameraHardwareInterface(const char *name):
85            mDevice(nullptr),
86            mHidlDevice(nullptr),
87            mName(name),
88            mPreviewScalingMode(NOT_SET),
89            mPreviewTransform(NOT_SET),
90            mPreviewWidth(NOT_SET),
91            mPreviewHeight(NOT_SET),
92            mPreviewFormat(NOT_SET),
93            mPreviewUsage(0),
94            mPreviewSwapInterval(NOT_SET),
95            mPreviewCrop{NOT_SET,NOT_SET,NOT_SET,NOT_SET}
96    {
97    }
98
99    ~CameraHardwareInterface();
100
101    status_t initialize(CameraModule *module);
102    status_t initialize(sp<CameraProviderManager> manager);
103
104    /** Set the ANativeWindow to which preview frames are sent */
105    status_t setPreviewWindow(const sp<ANativeWindow>& buf);
106
107    status_t setPreviewScalingMode(int scalingMode);
108
109    status_t setPreviewTransform(int transform);
110
111    /** Set the notification and data callbacks */
112    void setCallbacks(notify_callback notify_cb,
113                      data_callback data_cb,
114                      data_callback_timestamp data_cb_timestamp,
115                      void* user);
116
117    /**
118     * The following three functions all take a msgtype,
119     * which is a bitmask of the messages defined in
120     * include/ui/Camera.h
121     */
122
123    /**
124     * Enable a message, or set of messages.
125     */
126    void enableMsgType(int32_t msgType);
127
128    /**
129     * Disable a message, or a set of messages.
130     *
131     * Once received a call to disableMsgType(CAMERA_MSG_VIDEO_FRAME), camera hal
132     * should not rely on its client to call releaseRecordingFrame() to release
133     * video recording frames sent out by the cameral hal before and after the
134     * disableMsgType(CAMERA_MSG_VIDEO_FRAME) call. Camera hal clients must not
135     * modify/access any video recording frame after calling
136     * disableMsgType(CAMERA_MSG_VIDEO_FRAME).
137     */
138    void disableMsgType(int32_t msgType);
139
140    /**
141     * Query whether a message, or a set of messages, is enabled.
142     * Note that this is operates as an AND, if any of the messages
143     * queried are off, this will return false.
144     */
145    int msgTypeEnabled(int32_t msgType);
146
147    /**
148     * Start preview mode.
149     */
150    status_t startPreview();
151
152    /**
153     * Stop a previously started preview.
154     */
155    void stopPreview();
156
157    /**
158     * Returns true if preview is enabled.
159     */
160    int previewEnabled();
161
162    /**
163     * Request the camera hal to store meta data or real YUV data in
164     * the video buffers send out via CAMERA_MSG_VIDEO_FRRAME for a
165     * recording session. If it is not called, the default camera
166     * hal behavior is to store real YUV data in the video buffers.
167     *
168     * This method should be called before startRecording() in order
169     * to be effective.
170     *
171     * If meta data is stored in the video buffers, it is up to the
172     * receiver of the video buffers to interpret the contents and
173     * to find the actual frame data with the help of the meta data
174     * in the buffer. How this is done is outside of the scope of
175     * this method.
176     *
177     * Some camera hal may not support storing meta data in the video
178     * buffers, but all camera hal should support storing real YUV data
179     * in the video buffers. If the camera hal does not support storing
180     * the meta data in the video buffers when it is requested to do
181     * do, INVALID_OPERATION must be returned. It is very useful for
182     * the camera hal to pass meta data rather than the actual frame
183     * data directly to the video encoder, since the amount of the
184     * uncompressed frame data can be very large if video size is large.
185     *
186     * @param enable if true to instruct the camera hal to store
187     *      meta data in the video buffers; false to instruct
188     *      the camera hal to store real YUV data in the video
189     *      buffers.
190     *
191     * @return OK on success.
192     */
193
194    status_t storeMetaDataInBuffers(int enable);
195
196    /**
197     * Start record mode. When a record image is available a CAMERA_MSG_VIDEO_FRAME
198     * message is sent with the corresponding frame. Every record frame must be released
199     * by a cameral hal client via releaseRecordingFrame() before the client calls
200     * disableMsgType(CAMERA_MSG_VIDEO_FRAME). After the client calls
201     * disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is camera hal's responsibility
202     * to manage the life-cycle of the video recording frames, and the client must
203     * not modify/access any video recording frames.
204     */
205    status_t startRecording();
206
207    /**
208     * Stop a previously started recording.
209     */
210    void stopRecording();
211
212    /**
213     * Returns true if recording is enabled.
214     */
215    int recordingEnabled();
216
217    /**
218     * Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
219     *
220     * It is camera hal client's responsibility to release video recording
221     * frames sent out by the camera hal before the camera hal receives
222     * a call to disableMsgType(CAMERA_MSG_VIDEO_FRAME). After it receives
223     * the call to disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is camera hal's
224     * responsibility of managing the life-cycle of the video recording
225     * frames.
226     */
227    void releaseRecordingFrame(const sp<IMemory>& mem);
228
229    /**
230     * Start auto focus, the notification callback routine is called
231     * with CAMERA_MSG_FOCUS once when focusing is complete. autoFocus()
232     * will be called again if another auto focus is needed.
233     */
234    status_t autoFocus();
235
236    /**
237     * Cancels auto-focus function. If the auto-focus is still in progress,
238     * this function will cancel it. Whether the auto-focus is in progress
239     * or not, this function will return the focus position to the default.
240     * If the camera does not support auto-focus, this is a no-op.
241     */
242    status_t cancelAutoFocus();
243
244    /**
245     * Take a picture.
246     */
247    status_t takePicture();
248
249    /**
250     * Cancel a picture that was started with takePicture.  Calling this
251     * method when no picture is being taken is a no-op.
252     */
253    status_t cancelPicture();
254
255    /**
256     * Set the camera parameters. This returns BAD_VALUE if any parameter is
257     * invalid or not supported. */
258    status_t setParameters(const CameraParameters &params);
259
260    /** Return the camera parameters. */
261    CameraParameters getParameters() const;
262
263    /**
264     * Send command to camera driver.
265     */
266    status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2);
267
268    /**
269     * Release the hardware resources owned by this object.  Note that this is
270     * *not* done in the destructor.
271     */
272    void release();
273
274    /**
275     * Dump state of the camera hardware
276     */
277    status_t dump(int fd, const Vector<String16>& /*args*/) const;
278
279private:
280    camera_device_t *mDevice;
281    sp<hardware::camera::device::V1_0::ICameraDevice> mHidlDevice;
282    String8 mName;
283
284    static void sNotifyCb(int32_t msg_type, int32_t ext1,
285                            int32_t ext2, void *user);
286
287    static void sDataCb(int32_t msg_type,
288                          const camera_memory_t *data, unsigned int index,
289                          camera_frame_metadata_t *metadata,
290                          void *user);
291
292    static void sDataCbTimestamp(nsecs_t timestamp, int32_t msg_type,
293                             const camera_memory_t *data, unsigned index,
294                             void *user);
295
296    // TODO: b/35625849
297    // Meta data buffer layout for passing a native_handle to codec
298    // matching frameworks/native/include/media/hardware/MetadataBufferType.h and
299    //          frameworks/native/include/media/hardware/HardwareAPI.h
300    struct VideoNativeHandleMetadata {
301        static const uint32_t kMetadataBufferTypeNativeHandleSource = 3;
302        uint32_t eType; // must be kMetadataBufferTypeNativeHandleSource
303        native_handle_t* pHandle;
304    };
305
306    // This is a utility class that combines a MemoryHeapBase and a MemoryBase
307    // in one.  Since we tend to use them in a one-to-one relationship, this is
308    // handy.
309    class CameraHeapMemory : public RefBase {
310    public:
311        CameraHeapMemory(int fd, size_t buf_size, uint_t num_buffers = 1) :
312                         mBufSize(buf_size),
313                         mNumBufs(num_buffers)
314        {
315            mHeap = new MemoryHeapBase(fd, buf_size * num_buffers);
316            commonInitialization();
317        }
318
319        explicit CameraHeapMemory(size_t buf_size, uint_t num_buffers = 1) :
320                                  mBufSize(buf_size),
321                                  mNumBufs(num_buffers)
322        {
323            mHeap = new MemoryHeapBase(buf_size * num_buffers);
324            commonInitialization();
325        }
326
327        void commonInitialization()
328        {
329            handle.data = mHeap->base();
330            handle.size = mBufSize * mNumBufs;
331            handle.handle = this;
332
333            mBuffers = new sp<MemoryBase>[mNumBufs];
334            for (uint_t i = 0; i < mNumBufs; i++)
335                mBuffers[i] = new MemoryBase(mHeap,
336                                             i * mBufSize,
337                                             mBufSize);
338
339            handle.release = sPutMemory;
340        }
341
342        virtual ~CameraHeapMemory()
343        {
344            delete [] mBuffers;
345        }
346
347        size_t mBufSize;
348        uint_t mNumBufs;
349        sp<MemoryHeapBase> mHeap;
350        sp<MemoryBase> *mBuffers;
351
352        camera_memory_t handle;
353    };
354
355    static camera_memory_t* sGetMemory(int fd, size_t buf_size, uint_t num_bufs,
356                                         void *user __attribute__((unused)));
357
358    static void sPutMemory(camera_memory_t *data);
359
360    static ANativeWindow *sToAnw(void *user);
361
362    static int sDequeueBuffer(struct preview_stream_ops* w,
363                                buffer_handle_t** buffer, int *stride);
364
365    static int sLockBuffer(struct preview_stream_ops* w,
366                      buffer_handle_t* /*buffer*/);
367
368    static int sEnqueueBuffer(struct preview_stream_ops* w,
369                      buffer_handle_t* buffer);
370
371    static int sCancelBuffer(struct preview_stream_ops* w,
372                      buffer_handle_t* buffer);
373
374    static int sSetBufferCount(struct preview_stream_ops* w, int count);
375
376    static int sSetBuffersGeometry(struct preview_stream_ops* w,
377                      int width, int height, int format);
378
379    static int sSetCrop(struct preview_stream_ops *w,
380                      int left, int top, int right, int bottom);
381
382    static int sSetTimestamp(struct preview_stream_ops *w,
383                               int64_t timestamp);
384
385    static int sSetUsage(struct preview_stream_ops* w, int usage);
386
387    static int sSetSwapInterval(struct preview_stream_ops *w, int interval);
388
389    static int sGetMinUndequeuedBufferCount(
390                      const struct preview_stream_ops *w,
391                      int *count);
392
393    void initHalPreviewWindow();
394
395    std::pair<bool, uint64_t> getBufferId(ANativeWindowBuffer* anb);
396    void cleanupCirculatingBuffers();
397
398    /**
399     * Implementation of android::hardware::camera::device::V1_0::ICameraDeviceCallback
400     */
401    hardware::Return<void> notifyCallback(
402            hardware::camera::device::V1_0::NotifyCallbackMsg msgType,
403            int32_t ext1, int32_t ext2) override;
404    hardware::Return<uint32_t> registerMemory(
405            const hardware::hidl_handle& descriptor,
406            uint32_t bufferSize, uint32_t bufferCount) override;
407    hardware::Return<void> unregisterMemory(uint32_t memId) override;
408    hardware::Return<void> dataCallback(
409            hardware::camera::device::V1_0::DataCallbackMsg msgType,
410            uint32_t data, uint32_t bufferIndex,
411            const hardware::camera::device::V1_0::CameraFrameMetadata& metadata) override;
412    hardware::Return<void> dataCallbackTimestamp(
413            hardware::camera::device::V1_0::DataCallbackMsg msgType,
414            uint32_t data, uint32_t bufferIndex, int64_t timestamp) override;
415    hardware::Return<void> handleCallbackTimestamp(
416            hardware::camera::device::V1_0::DataCallbackMsg msgType,
417            const hardware::hidl_handle& frameData, uint32_t data,
418            uint32_t bufferIndex, int64_t timestamp) override;
419
420    /**
421     * Implementation of android::hardware::camera::device::V1_0::ICameraDevicePreviewCallback
422     */
423    hardware::Return<void> dequeueBuffer(dequeueBuffer_cb _hidl_cb) override;
424    hardware::Return<hardware::camera::common::V1_0::Status>
425            enqueueBuffer(uint64_t bufferId) override;
426    hardware::Return<hardware::camera::common::V1_0::Status>
427            cancelBuffer(uint64_t bufferId) override;
428    hardware::Return<hardware::camera::common::V1_0::Status>
429            setBufferCount(uint32_t count) override;
430    hardware::Return<hardware::camera::common::V1_0::Status>
431            setBuffersGeometry(uint32_t w, uint32_t h,
432                    hardware::graphics::common::V1_0::PixelFormat format) override;
433    hardware::Return<hardware::camera::common::V1_0::Status>
434            setCrop(int32_t left, int32_t top, int32_t right, int32_t bottom) override;
435    hardware::Return<hardware::camera::common::V1_0::Status>
436            setUsage(hardware::graphics::allocator::V2_0::ProducerUsage usage) override;
437    hardware::Return<hardware::camera::common::V1_0::Status>
438            setSwapInterval(int32_t interval) override;
439    hardware::Return<void> getMinUndequeuedBufferCount(
440        getMinUndequeuedBufferCount_cb _hidl_cb) override;
441    hardware::Return<hardware::camera::common::V1_0::Status>
442            setTimestamp(int64_t timestamp) override;
443
444    sp<ANativeWindow>        mPreviewWindow;
445
446    struct camera_preview_window {
447        struct preview_stream_ops nw;
448        void *user;
449    };
450
451    struct camera_preview_window mHalPreviewWindow;
452
453    notify_callback         mNotifyCb;
454    data_callback           mDataCb;
455    data_callback_timestamp mDataCbTimestamp;
456    void *mCbUser;
457
458    // Cached values for preview stream parameters
459    static const int NOT_SET = -1;
460    int mPreviewScalingMode;
461    int mPreviewTransform;
462    int mPreviewWidth;
463    int mPreviewHeight;
464    int mPreviewFormat;
465    int mPreviewUsage;
466    int mPreviewSwapInterval;
467    android_native_rect_t mPreviewCrop;
468
469    struct BufferHasher {
470        size_t operator()(const buffer_handle_t& buf) const {
471            if (buf == nullptr)
472                return 0;
473
474            size_t result = 1;
475            result = 31 * result + buf->numFds;
476            result = 31 * result + buf->numInts;
477            int length = buf->numFds + buf->numInts;
478            for (int i = 0; i < length; i++) {
479                result = 31 * result + buf->data[i];
480            }
481            return result;
482        }
483    };
484
485    struct BufferComparator {
486        bool operator()(const buffer_handle_t& buf1, const buffer_handle_t& buf2) const {
487            if (buf1->numFds == buf2->numFds && buf1->numInts == buf2->numInts) {
488                int length = buf1->numFds + buf1->numInts;
489                for (int i = 0; i < length; i++) {
490                    if (buf1->data[i] != buf2->data[i]) {
491                        return false;
492                    }
493                }
494                return true;
495            }
496            return false;
497        }
498    };
499
500    std::mutex mBufferIdMapLock; // protecting mBufferIdMap and mNextBufferId
501    typedef std::unordered_map<const buffer_handle_t, uint64_t,
502            BufferHasher, BufferComparator> BufferIdMap;
503    // stream ID -> per stream buffer ID map
504    BufferIdMap mBufferIdMap;
505    std::unordered_map<uint64_t, ANativeWindowBuffer*> mReversedBufMap;
506    uint64_t mNextBufferId = 1;
507    static const uint64_t BUFFER_ID_NO_BUFFER = 0;
508
509    std::unordered_map<int, camera_memory_t*> mHidlMemPoolMap;
510};
511
512};  // namespace android
513
514#endif
515