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