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