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