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