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