CameraHal.h revision 524cc0cda6ed8cb07e0469fc931657ac60335aa1
1/*
2 * Copyright (C) Texas Instruments - http://www.ti.com/
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
18
19#ifndef ANDROID_HARDWARE_CAMERA_HARDWARE_H
20#define ANDROID_HARDWARE_CAMERA_HARDWARE_H
21
22#include <stdio.h>
23#include <stdarg.h>
24#include <stdlib.h>
25#include <string.h>
26#include <unistd.h>
27#include <time.h>
28#include <fcntl.h>
29#include <sys/ioctl.h>
30#include <sys/mman.h>
31#include <sys/stat.h>
32#include <utils/Log.h>
33#include <utils/threads.h>
34#include <linux/videodev2.h>
35#include "binder/MemoryBase.h"
36#include "binder/MemoryHeapBase.h"
37#include <utils/threads.h>
38#include <camera/CameraParameters.h>
39#include <hardware/camera.h>
40#include "MessageQueue.h"
41#include "Semaphore.h"
42#include "CameraProperties.h"
43#include "DebugUtils.h"
44#include "SensorListener.h"
45
46#define MIN_WIDTH           640
47#define MIN_HEIGHT          480
48#define PICTURE_WIDTH   3264 /* 5mp - 2560. 8mp - 3280 */ /* Make sure it is a multiple of 16. */
49#define PICTURE_HEIGHT  2448 /* 5mp - 2048. 8mp - 2464 */ /* Make sure it is a multiple of 16. */
50#define PREVIEW_WIDTH 176
51#define PREVIEW_HEIGHT 144
52#define PIXEL_FORMAT           V4L2_PIX_FMT_UYVY
53
54#define VIDEO_FRAME_COUNT_MAX    8 //NUM_OVERLAY_BUFFERS_REQUESTED
55#define MAX_CAMERA_BUFFERS    8 //NUM_OVERLAY_BUFFERS_REQUESTED
56#define MAX_ZOOM        3
57#define THUMB_WIDTH     80
58#define THUMB_HEIGHT    60
59#define PIX_YUV422I 0
60#define PIX_YUV420P 1
61
62#define SATURATION_OFFSET 100
63#define SHARPNESS_OFFSET 100
64#define CONTRAST_OFFSET 100
65
66#define CAMHAL_GRALLOC_USAGE GRALLOC_USAGE_HW_TEXTURE | \
67                             GRALLOC_USAGE_EXTERNAL_DISP | \
68                             GRALLOC_USAGE_HW_RENDER | \
69                             GRALLOC_USAGE_SW_READ_RARELY | \
70                             GRALLOC_USAGE_SW_WRITE_NEVER
71
72//Enables Absolute PPM measurements in logcat
73#define PPM_INSTRUMENTATION_ABS 1
74
75//Uncomment to enable more verbose/debug logs
76//#define DEBUG_LOG
77
78///Camera HAL Logging Functions
79#ifndef DEBUG_LOG
80
81#define CAMHAL_LOGDA(str)
82#define CAMHAL_LOGDB(str, ...)
83#define CAMHAL_LOGVA(str)
84#define CAMHAL_LOGVB(str, ...)
85
86#define CAMHAL_LOGEA LOGE
87#define CAMHAL_LOGEB LOGE
88
89#undef LOG_FUNCTION_NAME
90#undef LOG_FUNCTION_NAME_EXIT
91#define LOG_FUNCTION_NAME
92#define LOG_FUNCTION_NAME_EXIT
93
94#else
95
96#define CAMHAL_LOGDA DBGUTILS_LOGDA
97#define CAMHAL_LOGDB DBGUTILS_LOGDB
98#define CAMHAL_LOGVA DBGUTILS_LOGVA
99#define CAMHAL_LOGVB DBGUTILS_LOGVB
100
101#define CAMHAL_LOGEA DBGUTILS_LOGEA
102#define CAMHAL_LOGEB DBGUTILS_LOGEB
103
104#endif
105
106
107
108#define NONNEG_ASSIGN(x,y) \
109    if(x > -1) \
110        y = x
111
112namespace android {
113
114#define PARAM_BUFFER            6000
115
116///Forward declarations
117class CameraHal;
118class CameraFrame;
119class CameraHalEvent;
120class DisplayFrame;
121
122class CameraArea : public RefBase
123{
124public:
125
126    CameraArea(ssize_t top,
127               ssize_t left,
128               ssize_t bottom,
129               ssize_t right,
130               size_t weight) : mTop(top),
131                                mLeft(left),
132                                mBottom(bottom),
133                                mRight(right),
134                                mWeight(weight) {}
135
136    status_t transfrom(size_t width,
137                       size_t height,
138                       size_t &top,
139                       size_t &left,
140                       size_t &areaWidth,
141                       size_t &areaHeight);
142
143    bool isValid()
144        {
145        return ( ( 0 != mTop ) || ( 0 != mLeft ) || ( 0 != mBottom ) || ( 0 != mRight) );
146        }
147
148    bool isZeroArea()
149    {
150        return  ( (0 == mTop ) && ( 0 == mLeft ) && ( 0 == mBottom )
151                 && ( 0 == mRight ) && ( 0 == mWeight ));
152    }
153
154    size_t getWeight()
155        {
156        return mWeight;
157        }
158
159    static status_t parseFocusArea(const char *area,
160                                   size_t areaLength,
161                                   Vector< sp<CameraArea> > &areas);
162
163    static status_t checkArea(ssize_t top,
164                              ssize_t left,
165                              ssize_t bottom,
166                              ssize_t right,
167                              ssize_t weight);
168
169private:
170
171    static const ssize_t TOP = -1000;
172    static const ssize_t LEFT = -1000;
173    static const ssize_t BOTTOM = 1000;
174    static const ssize_t RIGHT = 1000;
175    static const ssize_t WEIGHT_MIN = 1;
176    static const ssize_t WEIGHT_MAX = 1000;
177
178    ssize_t mTop;
179    ssize_t mLeft;
180    ssize_t mBottom;
181    ssize_t mRight;
182    size_t mWeight;
183};
184
185class CameraFDResult : public RefBase
186{
187public:
188
189    CameraFDResult() : mFaceData(NULL) {};
190    CameraFDResult(camera_frame_metadata_t *faces) : mFaceData(faces) {};
191
192    virtual ~CameraFDResult() {
193        if ( ( NULL != mFaceData ) && ( NULL != mFaceData->faces ) ) {
194            free(mFaceData->faces);
195            free(mFaceData);
196            mFaceData=NULL;
197        }
198
199        if(( NULL != mFaceData ))
200            {
201            free(mFaceData);
202            mFaceData = NULL;
203            }
204    }
205
206    camera_frame_metadata_t *getFaceResult() { return mFaceData; };
207
208    static const ssize_t TOP = -1000;
209    static const ssize_t LEFT = -1000;
210    static const ssize_t BOTTOM = 1000;
211    static const ssize_t RIGHT = 1000;
212    static const ssize_t INVALID_DATA = -2000;
213
214private:
215
216    camera_frame_metadata_t *mFaceData;
217};
218
219class CameraFrame
220{
221    public:
222
223    enum FrameType
224        {
225            PREVIEW_FRAME_SYNC = 0x1, ///SYNC implies that the frame needs to be explicitly returned after consuming in order to be filled by camera again
226            PREVIEW_FRAME = 0x2   , ///Preview frame includes viewfinder and snapshot frames
227            IMAGE_FRAME_SYNC = 0x4, ///Image Frame is the image capture output frame
228            IMAGE_FRAME = 0x8,
229            VIDEO_FRAME_SYNC = 0x10, ///Timestamp will be updated for these frames
230            VIDEO_FRAME = 0x20,
231            FRAME_DATA_SYNC = 0x40, ///Any extra data assosicated with the frame. Always synced with the frame
232            FRAME_DATA= 0x80,
233            RAW_FRAME = 0x100,
234            SNAPSHOT_FRAME = 0x200,
235            ALL_FRAMES = 0xFFFF   ///Maximum of 16 frame types supported
236        };
237
238    enum FrameQuirks
239    {
240        ENCODE_RAW_YUV422I_TO_JPEG = 0x1 << 0,
241        HAS_EXIF_DATA = 0x1 << 1,
242    };
243
244    //default contrustor
245    CameraFrame():
246    mCookie(NULL),
247    mCookie2(NULL),
248    mBuffer(NULL),
249    mFrameType(0),
250    mTimestamp(0),
251    mWidth(0),
252    mHeight(0),
253    mOffset(0),
254    mAlignment(0),
255    mFd(0),
256    mLength(0),
257    mFrameMask(0),
258    mQuirks(0) {}
259
260    //copy constructor
261    CameraFrame(const CameraFrame &frame) :
262    mCookie(frame.mCookie),
263    mCookie2(frame.mCookie2),
264    mBuffer(frame.mBuffer),
265    mFrameType(frame.mFrameType),
266    mTimestamp(frame.mTimestamp),
267    mWidth(frame.mWidth),
268    mHeight(frame.mHeight),
269    mOffset(frame.mOffset),
270    mAlignment(frame.mAlignment),
271    mFd(frame.mFd),
272    mLength(frame.mLength),
273    mFrameMask(frame.mFrameMask),
274    mQuirks(frame.mQuirks) {}
275
276    void *mCookie;
277    void *mCookie2;
278    void *mBuffer;
279    int mFrameType;
280    nsecs_t mTimestamp;
281    unsigned int mWidth, mHeight;
282    uint32_t mOffset;
283    unsigned int mAlignment;
284    int mFd;
285    size_t mLength;
286    unsigned mFrameMask;
287    unsigned int mQuirks;
288    ///@todo add other member vars like  stride etc
289};
290
291enum CameraHalError
292{
293    CAMERA_ERROR_FATAL = 0x1, //Fatal errors can only be recovered by restarting media server
294    CAMERA_ERROR_HARD = 0x2,  // Hard errors are hardware hangs that may be recoverable by resetting the hardware internally within the adapter
295    CAMERA_ERROR_SOFT = 0x4, // Soft errors are non fatal errors that can be recovered from without needing to stop use-case
296};
297
298///Common Camera Hal Event class which is visible to CameraAdapter,DisplayAdapter and AppCallbackNotifier
299///@todo Rename this class to CameraEvent
300class CameraHalEvent
301{
302public:
303    //Enums
304    enum CameraHalEventType {
305        NO_EVENTS = 0x0,
306        EVENT_FOCUS_LOCKED = 0x1,
307        EVENT_FOCUS_ERROR = 0x2,
308        EVENT_ZOOM_INDEX_REACHED = 0x4,
309        EVENT_SHUTTER = 0x8,
310        EVENT_FACE = 0x10,
311        ///@remarks Future enum related to display, like frame displayed event, could be added here
312        ALL_EVENTS = 0xFFFF ///Maximum of 16 event types supported
313    };
314
315    ///Class declarations
316    ///@remarks Add a new class for a new event type added above
317
318    //Shutter event specific data
319    typedef struct ShutterEventData_t {
320        bool shutterClosed;
321    }ShutterEventData;
322
323    ///Focus event specific data
324    typedef struct FocusEventData_t {
325        bool focusLocked;
326        bool focusError;
327        int currentFocusValue;
328    } FocusEventData;
329
330    ///Zoom specific event data
331    typedef struct ZoomEventData_t {
332        int currentZoomIndex;
333        bool targetZoomIndexReached;
334    } ZoomEventData;
335
336    typedef struct FaceData_t {
337        ssize_t top;
338        ssize_t left;
339        ssize_t bottom;
340        ssize_t right;
341        size_t score;
342    } FaceData;
343
344    typedef sp<CameraFDResult> FaceEventData;
345
346    class CameraHalEventData : public RefBase{
347
348    public:
349
350        CameraHalEvent::FocusEventData focusEvent;
351        CameraHalEvent::ZoomEventData zoomEvent;
352        CameraHalEvent::ShutterEventData shutterEvent;
353        CameraHalEvent::FaceEventData faceEvent;
354    };
355
356    //default contrustor
357    CameraHalEvent():
358    mCookie(NULL),
359    mEventType(NO_EVENTS) {}
360
361    //copy constructor
362    CameraHalEvent(const CameraHalEvent &event) :
363        mCookie(event.mCookie),
364        mEventType(event.mEventType),
365        mEventData(event.mEventData) {};
366
367    void* mCookie;
368    CameraHalEventType mEventType;
369    sp<CameraHalEventData> mEventData;
370
371};
372
373///      Have a generic callback class based on template - to adapt CameraFrame and Event
374typedef void (*frame_callback) (CameraFrame *cameraFrame);
375typedef void (*event_callback) (CameraHalEvent *event);
376
377//signals CameraHAL to relase image buffers
378typedef void (*release_image_buffers_callback) (void *userData);
379typedef void (*end_image_capture_callback) (void *userData);
380
381/**
382  * Interface class implemented by classes that have some events to communicate to dependendent classes
383  * Dependent classes use this interface for registering for events
384  */
385class MessageNotifier
386{
387public:
388    static const uint32_t EVENT_BIT_FIELD_POSITION;
389    static const uint32_t FRAME_BIT_FIELD_POSITION;
390
391    ///@remarks Msg type comes from CameraFrame and CameraHalEvent classes
392    ///           MSB 16 bits is for events and LSB 16 bits is for frame notifications
393    ///         FrameProvider and EventProvider classes act as helpers to event/frame
394    ///         consumers to call this api
395    virtual void enableMsgType(int32_t msgs, frame_callback frameCb=NULL, event_callback eventCb=NULL, void* cookie=NULL) = 0;
396    virtual void disableMsgType(int32_t msgs, void* cookie) = 0;
397
398    virtual ~MessageNotifier() {};
399};
400
401class ErrorNotifier : public virtual RefBase
402{
403public:
404    virtual void errorNotify(int error) = 0;
405
406    virtual ~ErrorNotifier() {};
407};
408
409
410/**
411  * Interace class abstraction for Camera Adapter to act as a frame provider
412  * This interface is fully implemented by Camera Adapter
413  */
414class FrameNotifier : public MessageNotifier
415{
416public:
417    virtual void returnFrame(void* frameBuf, CameraFrame::FrameType frameType) = 0;
418
419    virtual ~FrameNotifier() {};
420};
421
422/**   * Wrapper class around Frame Notifier, which is used by display and notification classes for interacting with Camera Adapter
423  */
424class FrameProvider
425{
426    FrameNotifier* mFrameNotifier;
427    void* mCookie;
428    frame_callback mFrameCallback;
429
430public:
431    FrameProvider(FrameNotifier *fn, void* cookie, frame_callback frameCallback)
432        :mFrameNotifier(fn), mCookie(cookie),mFrameCallback(frameCallback) { }
433
434    int enableFrameNotification(int32_t frameTypes);
435    int disableFrameNotification(int32_t frameTypes);
436    int returnFrame(void *frameBuf, CameraFrame::FrameType frameType);
437};
438
439/** Wrapper class around MessageNotifier, which is used by display and notification classes for interacting with
440   *  Camera Adapter
441  */
442class EventProvider
443{
444public:
445    MessageNotifier* mEventNotifier;
446    void* mCookie;
447    event_callback mEventCallback;
448
449public:
450    EventProvider(MessageNotifier *mn, void* cookie, event_callback eventCallback)
451        :mEventNotifier(mn), mCookie(cookie), mEventCallback(eventCallback) {}
452
453    int enableEventNotification(int32_t eventTypes);
454    int disableEventNotification(int32_t eventTypes);
455};
456
457/*
458  * Interface for providing buffers
459  */
460class BufferProvider
461{
462public:
463    virtual void* allocateBuffer(int width, int height, const char* format, int &bytes, int numBufs) = 0;
464
465    //additional methods used for memory mapping
466    virtual uint32_t * getOffsets() = 0;
467    virtual int getFd() = 0;
468
469    virtual int freeBuffer(void* buf) = 0;
470
471    virtual ~BufferProvider() {}
472};
473
474/**
475  * Class for handling data and notify callbacks to application
476  */
477class   AppCallbackNotifier: public ErrorNotifier , public virtual RefBase
478{
479
480public:
481
482    ///Constants
483    static const int NOTIFIER_TIMEOUT;
484    static const int32_t MAX_BUFFERS = 8;
485
486    enum NotifierCommands
487        {
488        NOTIFIER_CMD_PROCESS_EVENT,
489        NOTIFIER_CMD_PROCESS_FRAME,
490        NOTIFIER_CMD_PROCESS_ERROR
491        };
492
493    enum NotifierState
494        {
495        NOTIFIER_STOPPED,
496        NOTIFIER_STARTED,
497        NOTIFIER_EXITED
498        };
499
500public:
501
502    ~AppCallbackNotifier();
503
504    ///Initialzes the callback notifier, creates any resources required
505    status_t initialize();
506
507    ///Starts the callbacks to application
508    status_t start();
509
510    ///Stops the callbacks from going to application
511    status_t stop();
512
513    void setEventProvider(int32_t eventMask, MessageNotifier * eventProvider);
514    void setFrameProvider(FrameNotifier *frameProvider);
515
516    //All sub-components of Camera HAL call this whenever any error happens
517    virtual void errorNotify(int error);
518
519    status_t startPreviewCallbacks(CameraParameters &params, void *buffers, uint32_t *offsets, int fd, size_t length, size_t count);
520    status_t stopPreviewCallbacks();
521
522    status_t enableMsgType(int32_t msgType);
523    status_t disableMsgType(int32_t msgType);
524
525    //API for enabling/disabling measurement data
526    void setMeasurements(bool enable);
527
528    //thread loops
529    bool notificationThread();
530
531    ///Notification callback functions
532    static void frameCallbackRelay(CameraFrame* caFrame);
533    static void eventCallbackRelay(CameraHalEvent* chEvt);
534    void frameCallback(CameraFrame* caFrame);
535    void eventCallback(CameraHalEvent* chEvt);
536    void flushAndReturnFrames();
537
538    void setCallbacks(CameraHal *cameraHal,
539                        camera_notify_callback notify_cb,
540                        camera_data_callback data_cb,
541                        camera_data_timestamp_callback data_cb_timestamp,
542                        camera_request_memory get_memory,
543                        void *user);
544
545    //Set Burst mode
546    void setBurst(bool burst);
547
548    int setParameters(const CameraParameters& params);
549
550    //Notifications from CameraHal for video recording case
551    status_t startRecording();
552    status_t stopRecording();
553    status_t initSharedVideoBuffers(void *buffers, uint32_t *offsets, int fd, size_t length, size_t count);
554    status_t releaseRecordingFrame(const void *opaque);
555
556	status_t useMetaDataBufferMode(bool enable);
557
558    void EncoderDoneCb(size_t jpeg_size, uint8_t* src, CameraFrame::FrameType type, void* cookie1, void* cookie2);
559
560    //Internal class definitions
561    class NotificationThread : public Thread {
562        AppCallbackNotifier* mAppCallbackNotifier;
563        TIUTILS::MessageQueue mNotificationThreadQ;
564    public:
565        enum NotificationThreadCommands
566        {
567        NOTIFIER_START,
568        NOTIFIER_STOP,
569        NOTIFIER_EXIT,
570        };
571    public:
572        NotificationThread(AppCallbackNotifier* nh)
573            : Thread(false), mAppCallbackNotifier(nh) { }
574        virtual bool threadLoop() {
575            return mAppCallbackNotifier->notificationThread();
576        }
577
578        TIUTILS::MessageQueue &msgQ() { return mNotificationThreadQ;}
579    };
580
581    //Friend declarations
582    friend class NotificationThread;
583
584private:
585    void notifyEvent();
586    void notifyFrame();
587    bool processMessage();
588    void releaseSharedVideoBuffers();
589    status_t dummyRaw();
590    void copyAndSendPictureFrame(CameraFrame* frame, int32_t msgType);
591    void copyAndSendPreviewFrame(CameraFrame* frame, int32_t msgType);
592
593private:
594    mutable Mutex mLock;
595    mutable Mutex mBurstLock;
596    CameraHal* mCameraHal;
597    camera_notify_callback mNotifyCb;
598    camera_data_callback   mDataCb;
599    camera_data_timestamp_callback mDataCbTimestamp;
600    camera_request_memory mRequestMemory;
601    void *mCallbackCookie;
602
603    //Keeps Video MemoryHeaps and Buffers within
604    //these objects
605    KeyedVector<unsigned int, unsigned int> mVideoHeaps;
606    KeyedVector<unsigned int, unsigned int> mVideoBuffers;
607    KeyedVector<unsigned int, unsigned int> mVideoMap;
608
609    //Keeps list of Gralloc handles and associated Video Metadata Buffers
610    KeyedVector<uint32_t, uint32_t> mVideoMetadataBufferMemoryMap;
611    KeyedVector<uint32_t, uint32_t> mVideoMetadataBufferReverseMap;
612
613    bool mBufferReleased;
614
615    sp< NotificationThread> mNotificationThread;
616    EventProvider *mEventProvider;
617    FrameProvider *mFrameProvider;
618    TIUTILS::MessageQueue mEventQ;
619    TIUTILS::MessageQueue mFrameQ;
620    NotifierState mNotifierState;
621
622    bool mPreviewing;
623    camera_memory_t* mPreviewMemory;
624    unsigned char* mPreviewBufs[MAX_BUFFERS];
625    int mPreviewBufCount;
626    const char *mPreviewPixelFormat;
627    KeyedVector<unsigned int, sp<MemoryHeapBase> > mSharedPreviewHeaps;
628    KeyedVector<unsigned int, sp<MemoryBase> > mSharedPreviewBuffers;
629
630    //Burst mode active
631    bool mBurst;
632    mutable Mutex mRecordingLock;
633    bool mRecording;
634    bool mMeasurementEnabled;
635
636    bool mUseMetaDataBufferMode;
637    bool mRawAvailable;
638
639    CameraParameters mParameters;
640
641};
642
643
644/**
645  * Class used for allocating memory for JPEG bit stream buffers, output buffers of camera in no overlay case
646  */
647class MemoryManager : public BufferProvider, public virtual RefBase
648{
649public:
650    MemoryManager():mIonFd(0){ }
651
652    ///Initializes the memory manager creates any resources required
653    status_t initialize() { return NO_ERROR; }
654
655    int setErrorHandler(ErrorNotifier *errorNotifier);
656    virtual void* allocateBuffer(int width, int height, const char* format, int &bytes, int numBufs);
657    virtual uint32_t * getOffsets();
658    virtual int getFd() ;
659    virtual int freeBuffer(void* buf);
660
661private:
662
663    sp<ErrorNotifier> mErrorNotifier;
664    int mIonFd;
665    KeyedVector<unsigned int, unsigned int> mIonHandleMap;
666    KeyedVector<unsigned int, unsigned int> mIonFdMap;
667    KeyedVector<unsigned int, unsigned int> mIonBufLength;
668};
669
670
671
672
673/**
674  * CameraAdapter interface class
675  * Concrete classes derive from this class and provide implementations based on the specific camera h/w interface
676  */
677
678class CameraAdapter: public FrameNotifier, public virtual RefBase
679{
680protected:
681    enum AdapterActiveStates {
682        INTIALIZED_ACTIVE =     1 << 0,
683        LOADED_PREVIEW_ACTIVE = 1 << 1,
684        PREVIEW_ACTIVE =        1 << 2,
685        LOADED_CAPTURE_ACTIVE = 1 << 3,
686        CAPTURE_ACTIVE =        1 << 4,
687        BRACKETING_ACTIVE =     1 << 5,
688        AF_ACTIVE =             1 << 6,
689        ZOOM_ACTIVE =           1 << 7,
690        VIDEO_ACTIVE =          1 << 8,
691    };
692public:
693    typedef struct
694        {
695         void *mBuffers;
696         uint32_t *mOffsets;
697         int mFd;
698         size_t mLength;
699         size_t mCount;
700         size_t mMaxQueueable;
701        } BuffersDescriptor;
702
703    enum CameraCommands
704        {
705        CAMERA_START_PREVIEW                        = 0,
706        CAMERA_STOP_PREVIEW                         = 1,
707        CAMERA_START_VIDEO                          = 2,
708        CAMERA_STOP_VIDEO                           = 3,
709        CAMERA_START_IMAGE_CAPTURE                  = 4,
710        CAMERA_STOP_IMAGE_CAPTURE                   = 5,
711        CAMERA_PERFORM_AUTOFOCUS                    = 6,
712        CAMERA_CANCEL_AUTOFOCUS                     = 7,
713        CAMERA_PREVIEW_FLUSH_BUFFERS                = 8,
714        CAMERA_START_SMOOTH_ZOOM                    = 9,
715        CAMERA_STOP_SMOOTH_ZOOM                     = 10,
716        CAMERA_USE_BUFFERS_PREVIEW                  = 11,
717        CAMERA_SET_TIMEOUT                          = 12,
718        CAMERA_CANCEL_TIMEOUT                       = 13,
719        CAMERA_START_BRACKET_CAPTURE                = 14,
720        CAMERA_STOP_BRACKET_CAPTURE                 = 15,
721        CAMERA_QUERY_RESOLUTION_PREVIEW             = 16,
722        CAMERA_QUERY_BUFFER_SIZE_IMAGE_CAPTURE      = 17,
723        CAMERA_QUERY_BUFFER_SIZE_PREVIEW_DATA       = 18,
724        CAMERA_USE_BUFFERS_IMAGE_CAPTURE            = 19,
725        CAMERA_USE_BUFFERS_PREVIEW_DATA             = 20,
726        CAMERA_TIMEOUT_EXPIRED                      = 21,
727        CAMERA_START_FD                             = 22,
728        CAMERA_STOP_FD                              = 23,
729        };
730
731    enum CameraMode
732        {
733        CAMERA_PREVIEW,
734        CAMERA_IMAGE_CAPTURE,
735        CAMERA_VIDEO,
736        CAMERA_MEASUREMENT
737        };
738
739    enum AdapterState {
740        INTIALIZED_STATE           = INTIALIZED_ACTIVE,
741        LOADED_PREVIEW_STATE       = LOADED_PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
742        PREVIEW_STATE              = PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
743        LOADED_CAPTURE_STATE       = LOADED_CAPTURE_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
744        CAPTURE_STATE              = CAPTURE_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
745        BRACKETING_STATE           = BRACKETING_ACTIVE | CAPTURE_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE ,
746        AF_STATE                   = AF_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
747        ZOOM_STATE                 = ZOOM_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
748        VIDEO_STATE                = VIDEO_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
749        VIDEO_ZOOM_STATE           = VIDEO_ACTIVE | ZOOM_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
750        VIDEO_LOADED_CAPTURE_STATE = VIDEO_ACTIVE | LOADED_CAPTURE_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
751        VIDEO_CAPTURE_STATE        = VIDEO_ACTIVE | CAPTURE_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
752        AF_ZOOM_STATE              = AF_ACTIVE | ZOOM_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
753        BRACKETING_ZOOM_STATE      = BRACKETING_ACTIVE | ZOOM_ACTIVE | PREVIEW_ACTIVE | INTIALIZED_ACTIVE,
754    };
755
756public:
757
758    ///Initialzes the camera adapter creates any resources required
759    virtual int initialize(CameraProperties::Properties*, int sensor_index=0) = 0;
760
761    virtual int setErrorHandler(ErrorNotifier *errorNotifier) = 0;
762
763    //Message/Frame notification APIs
764    virtual void enableMsgType(int32_t msgs,
765                               frame_callback callback = NULL,
766                               event_callback eventCb = NULL,
767                               void *cookie = NULL) = 0;
768    virtual void disableMsgType(int32_t msgs, void* cookie) = 0;
769    virtual void returnFrame(void* frameBuf, CameraFrame::FrameType frameType) = 0;
770
771    //APIs to configure Camera adapter and get the current parameter set
772    virtual int setParameters(const CameraParameters& params) = 0;
773    virtual void getParameters(CameraParameters& params) = 0;
774
775    //API to flush the buffers from Camera
776     status_t flushBuffers()
777        {
778        return sendCommand(CameraAdapter::CAMERA_PREVIEW_FLUSH_BUFFERS);
779        }
780
781    //Registers callback for returning image buffers back to CameraHAL
782    virtual int registerImageReleaseCallback(release_image_buffers_callback callback, void *user_data) = 0;
783
784    //Registers callback, which signals a completed image capture
785    virtual int registerEndCaptureCallback(end_image_capture_callback callback, void *user_data) = 0;
786
787    //API to send a command to the camera
788    virtual status_t sendCommand(CameraCommands operation, int value1=0, int value2=0, int value3=0) = 0;
789
790    virtual ~CameraAdapter() {};
791
792    //Retrieves the current Adapter state
793    virtual AdapterState getState() = 0;
794
795    //Retrieves the next Adapter state
796    virtual AdapterState getNextState() = 0;
797
798    // Receive orientation events from CameraHal
799    virtual void onOrientationEvent(uint32_t orientation, uint32_t tilt) = 0;
800protected:
801    //The first two methods will try to switch the adapter state.
802    //Every call to setState() should be followed by a corresponding
803    //call to commitState(). If the state switch fails, then it will
804    //get reset to the previous state via rollbackState().
805    virtual status_t setState(CameraCommands operation) = 0;
806    virtual status_t commitState() = 0;
807    virtual status_t rollbackState() = 0;
808
809    // Retrieves the current Adapter state - for internal use (not locked)
810    virtual status_t getState(AdapterState &state) = 0;
811    // Retrieves the next Adapter state - for internal use (not locked)
812    virtual status_t getNextState(AdapterState &state) = 0;
813};
814
815class DisplayAdapter : public BufferProvider, public virtual RefBase
816{
817public:
818    typedef struct S3DParameters_t
819    {
820        int mode;
821        int framePacking;
822        int order;
823        int subSampling;
824    } S3DParameters;
825
826    ///Initializes the display adapter creates any resources required
827    virtual int initialize() = 0;
828
829    virtual int setPreviewWindow(struct preview_stream_ops *window) = 0;
830    virtual int setFrameProvider(FrameNotifier *frameProvider) = 0;
831    virtual int setErrorHandler(ErrorNotifier *errorNotifier) = 0;
832    virtual int enableDisplay(int width, int height, struct timeval *refTime = NULL, S3DParameters *s3dParams = NULL) = 0;
833    virtual int disableDisplay(bool cancel_buffer = true) = 0;
834    //Used for Snapshot review temp. pause
835    virtual int pauseDisplay(bool pause) = 0;
836
837#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
838    //Used for shot to snapshot measurement
839    virtual int setSnapshotTimeRef(struct timeval *refTime = NULL) = 0;
840#endif
841
842    virtual int useBuffers(void *bufArr, int num) = 0;
843    virtual bool supportsExternalBuffering() = 0;
844
845    // Get max queueable buffers display supports
846    // This function should only be called after
847    // allocateBuffer
848    virtual int maxQueueableBuffers(unsigned int& queueable) = 0;
849};
850
851static void releaseImageBuffers(void *userData);
852
853static void endImageCapture(void *userData);
854
855 /**
856    Implementation of the Android Camera hardware abstraction layer
857
858    This class implements the interface methods defined in CameraHardwareInterface
859    for the OMAP4 platform
860
861*/
862class CameraHal
863
864{
865
866public:
867    ///Constants
868    static const int NO_BUFFERS_PREVIEW;
869    static const int NO_BUFFERS_IMAGE_CAPTURE;
870    static const uint32_t VFR_SCALE = 1000;
871
872
873    /*--------------------Interface Methods---------------------------------*/
874
875     //@{
876public:
877
878    /** Set the notification and data callbacks */
879    void setCallbacks(camera_notify_callback notify_cb,
880                        camera_data_callback data_cb,
881                        camera_data_timestamp_callback data_cb_timestamp,
882                        camera_request_memory get_memory,
883                        void *user);
884
885    /** Receives orientation events from SensorListener **/
886    void onOrientationEvent(uint32_t orientation, uint32_t tilt);
887
888    /**
889     * The following three functions all take a msgtype,
890     * which is a bitmask of the messages defined in
891     * include/ui/Camera.h
892     */
893
894    /**
895     * Enable a message, or set of messages.
896     */
897    void        enableMsgType(int32_t msgType);
898
899    /**
900     * Disable a message, or a set of messages.
901     */
902    void        disableMsgType(int32_t msgType);
903
904    /**
905     * Query whether a message, or a set of messages, is enabled.
906     * Note that this is operates as an AND, if any of the messages
907     * queried are off, this will return false.
908     */
909    int        msgTypeEnabled(int32_t msgType);
910
911    /**
912     * Start preview mode.
913     */
914    int    startPreview();
915
916    /**
917     * Only used if overlays are used for camera preview.
918     */
919    int setPreviewWindow(struct preview_stream_ops *window);
920
921    /**
922     * Stop a previously started preview.
923     */
924    void        stopPreview();
925
926    /**
927     * Returns true if preview is enabled.
928     */
929    bool        previewEnabled();
930
931    /**
932     * Start record mode. When a record image is available a CAMERA_MSG_VIDEO_FRAME
933     * message is sent with the corresponding frame. Every record frame must be released
934     * by calling releaseRecordingFrame().
935     */
936    int    startRecording();
937
938    /**
939     * Stop a previously started recording.
940     */
941    void        stopRecording();
942
943    /**
944     * Returns true if recording is enabled.
945     */
946    int        recordingEnabled();
947
948    /**
949     * Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
950     */
951    void        releaseRecordingFrame(const void *opaque);
952
953    /**
954     * Set the camera parameters specific to Video Recording.
955     */
956    bool        setVideoModeParameters();
957
958    /**
959     * Reset the camera parameters specific to Video Recording.
960     */
961    bool       resetVideoModeParameters();
962
963    /**
964     * Restart the preview with setParameter.
965     */
966    status_t        restartPreview();
967
968    /**
969     * Start auto focus, the notification callback routine is called
970     * with CAMERA_MSG_FOCUS once when focusing is complete. autoFocus()
971     * will be called again if another auto focus is needed.
972     */
973    int    autoFocus();
974
975    /**
976     * Cancels auto-focus function. If the auto-focus is still in progress,
977     * this function will cancel it. Whether the auto-focus is in progress
978     * or not, this function will return the focus position to the default.
979     * If the camera does not support auto-focus, this is a no-op.
980     */
981    int    cancelAutoFocus();
982
983    /**
984     * Take a picture.
985     */
986    int    takePicture();
987
988    /**
989     * Cancel a picture that was started with takePicture.  Calling this
990     * method when no picture is being taken is a no-op.
991     */
992    int    cancelPicture();
993
994    /** Set the camera parameters. */
995    int    setParameters(const char* params);
996    int    setParameters(const CameraParameters& params);
997
998    /** Return the camera parameters. */
999    char*  getParameters();
1000    void putParameters(char *);
1001
1002    /**
1003     * Send command to camera driver.
1004     */
1005    int sendCommand(int32_t cmd, int32_t arg1, int32_t arg2);
1006
1007    /**
1008     * Release the hardware resources owned by this object.  Note that this is
1009     * *not* done in the destructor.
1010     */
1011    void release();
1012
1013    /**
1014     * Dump state of the camera hardware
1015     */
1016    int dump(int fd) const;
1017
1018
1019		status_t storeMetaDataInBuffers(bool enable);
1020
1021     //@}
1022
1023/*--------------------Internal Member functions - Public---------------------------------*/
1024
1025public:
1026 /** @name internalFunctionsPublic */
1027  //@{
1028
1029    /** Constructor of CameraHal */
1030    CameraHal(int cameraId);
1031
1032    // Destructor of CameraHal
1033    ~CameraHal();
1034
1035    /** Initialize CameraHal */
1036    status_t initialize(CameraProperties::Properties*);
1037
1038    /** Deinitialize CameraHal */
1039    void deinitialize();
1040
1041#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
1042
1043    //Uses the constructor timestamp as a reference to calcluate the
1044    // elapsed time
1045    static void PPM(const char *);
1046    //Uses a user provided timestamp as a reference to calcluate the
1047    // elapsed time
1048    static void PPM(const char *, struct timeval*, ...);
1049
1050#endif
1051
1052    /** Free image bufs */
1053    status_t freeImageBufs();
1054
1055    //Signals the end of image capture
1056    status_t signalEndImageCapture();
1057
1058    //Events
1059    static void eventCallbackRelay(CameraHalEvent* event);
1060    void eventCallback(CameraHalEvent* event);
1061    void setEventProvider(int32_t eventMask, MessageNotifier * eventProvider);
1062
1063/*--------------------Internal Member functions - Private---------------------------------*/
1064private:
1065
1066    /** @name internalFunctionsPrivate */
1067    //@{
1068
1069    status_t parseResolution(const char *resStr, int &width, int &height);
1070
1071    void insertSupportedParams();
1072
1073    /** Allocate preview data buffers */
1074    status_t allocPreviewDataBufs(size_t size, size_t bufferCount);
1075
1076    /** Free preview data buffers */
1077    status_t freePreviewDataBufs();
1078
1079    /** Allocate preview buffers */
1080    status_t allocPreviewBufs(int width, int height, const char* previewFormat, unsigned int bufferCount, unsigned int &max_queueable);
1081
1082    /** Allocate video buffers */
1083    status_t allocVideoBufs(int width, int height, const char* previewFormat);
1084
1085    /** Allocate image capture buffers */
1086    status_t allocImageBufs(unsigned int width, unsigned int height, size_t length, const char* previewFormat, unsigned int bufferCount);
1087
1088    /** Free preview buffers */
1089    status_t freePreviewBufs();
1090
1091    /** Free video bufs */
1092    status_t freeVideoBufs();
1093
1094    //Check if a given resolution is supported by the current camera
1095    //instance
1096    bool isResolutionValid(unsigned int width, unsigned int height, const char *supportedResolutions);
1097
1098    //Check if a given parameter is supported by the current camera
1099    // instance
1100    bool isParameterValid(const char *param, const char *supportedParams);
1101    bool isParameterValid(int param, const char *supportedParams);
1102    status_t doesSetParameterNeedUpdate(const char *new_param, const char *old_params, bool &update);
1103
1104    /** Initialize default parameters */
1105    void initDefaultParameters();
1106
1107    void dumpProperties(CameraProperties::Properties& cameraProps);
1108
1109    status_t startImageBracketing();
1110
1111    status_t stopImageBracketing();
1112
1113    void setShutter(bool enable);
1114
1115    void forceStopPreview();
1116
1117    void selectFPSRange(int framerate, int *min_fps, int *max_fps);
1118
1119    //@}
1120
1121
1122/*----------Member variables - Public ---------------------*/
1123public:
1124    int32_t mMsgEnabled;
1125    bool mRecordEnabled;
1126    nsecs_t mCurrentTime;
1127    bool mFalsePreview;
1128    bool mPreviewEnabled;
1129    uint32_t mTakePictureQueue;
1130    bool mBracketingEnabled;
1131    bool mBracketingRunning;
1132    //User shutter override
1133    bool mShutterEnabled;
1134    bool mMeasurementEnabled;
1135    //Google's parameter delimiter
1136    static const char PARAMS_DELIMITER[];
1137
1138    CameraAdapter *mCameraAdapter;
1139    sp<AppCallbackNotifier> mAppCallbackNotifier;
1140    sp<DisplayAdapter> mDisplayAdapter;
1141    sp<MemoryManager> mMemoryManager;
1142
1143    sp<IMemoryHeap> mPictureHeap;
1144
1145    int* mGrallocHandles;
1146    bool mFpsRangeChangedByApp;
1147
1148
1149
1150
1151
1152///static member vars
1153
1154#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
1155
1156    //Timestamp from the CameraHal constructor
1157    static struct timeval ppm_start;
1158    //Timestamp of the autoFocus command
1159    static struct timeval mStartFocus;
1160    //Timestamp of the startPreview command
1161    static struct timeval mStartPreview;
1162    //Timestamp of the takePicture command
1163    static struct timeval mStartCapture;
1164
1165#endif
1166
1167/*----------Member variables - Private ---------------------*/
1168private:
1169    bool mDynamicPreviewSwitch;
1170    //keeps paused state of display
1171    bool mDisplayPaused;
1172    //Index of current camera adapter
1173    int mCameraIndex;
1174
1175    mutable Mutex mLock;
1176
1177    sp<SensorListener> mSensorListener;
1178
1179    void* mCameraAdapterHandle;
1180
1181    CameraParameters mParameters;
1182    bool mPreviewRunning;
1183    bool mPreviewStateOld;
1184    bool mRecordingEnabled;
1185    EventProvider *mEventProvider;
1186
1187    int32_t *mPreviewDataBufs;
1188    uint32_t *mPreviewDataOffsets;
1189    int mPreviewDataFd;
1190    int mPreviewDataLength;
1191    int32_t *mImageBufs;
1192    uint32_t *mImageOffsets;
1193    int mImageFd;
1194    int mImageLength;
1195    int32_t *mPreviewBufs;
1196    uint32_t *mPreviewOffsets;
1197    int mPreviewLength;
1198    int mPreviewFd;
1199    int32_t *mVideoBufs;
1200    uint32_t *mVideoOffsets;
1201    int mVideoFd;
1202    int mVideoLength;
1203
1204    int mBracketRangePositive;
1205    int mBracketRangeNegative;
1206
1207    ///@todo Rename this as preview buffer provider
1208    BufferProvider *mBufProvider;
1209    BufferProvider *mVideoBufProvider;
1210
1211
1212    CameraProperties::Properties* mCameraProperties;
1213
1214    bool mPreviewStartInProgress;
1215
1216    bool mSetPreviewWindowCalled;
1217
1218    uint32_t mPreviewWidth;
1219    uint32_t mPreviewHeight;
1220    int32_t mMaxZoomSupported;
1221};
1222
1223
1224}; // namespace android
1225
1226#endif
1227