Parameters.h revision fd6ecdd39bd83ea020f78b425e96310380d66c35
1/*
2 * Copyright (C) 2012 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#ifndef ANDROID_SERVERS_CAMERA_CAMERA2PARAMETERS_H
18#define ANDROID_SERVERS_CAMERA_CAMERA2PARAMETERS_H
19
20#include <system/graphics.h>
21
22#include <utils/Errors.h>
23#include <utils/Mutex.h>
24#include <utils/String8.h>
25#include <utils/Vector.h>
26#include <utils/KeyedVector.h>
27#include <camera/CameraParameters.h>
28#include <camera/CameraMetadata.h>
29
30namespace android {
31namespace camera2 {
32
33/**
34 * Current camera state; this is the full state of the Camera under the old
35 * camera API (contents of the CameraParameters object in a more-efficient
36 * format, plus other state). The enum values are mostly based off the
37 * corresponding camera2 enums, not the camera1 strings. A few are defined here
38 * if they don't cleanly map to camera2 values.
39 */
40struct Parameters {
41    /**
42     * Parameters and other state
43     */
44    int cameraId;
45    int cameraFacing;
46
47    int previewWidth, previewHeight;
48    int32_t previewFpsRange[2];
49    int lastSetPreviewFps; // the last single FPS value seen in a set call
50    int previewFps; // deprecated, here only for tracking changes
51    int previewFormat;
52
53    int previewTransform; // set by CAMERA_CMD_SET_DISPLAY_ORIENTATION
54
55    int pictureWidth, pictureHeight;
56
57    int32_t jpegThumbSize[2];
58    uint8_t jpegQuality, jpegThumbQuality;
59    int32_t jpegRotation;
60
61    bool gpsEnabled;
62    double gpsCoordinates[3];
63    int64_t gpsTimestamp;
64    String8 gpsProcessingMethod;
65
66    uint8_t wbMode;
67    uint8_t effectMode;
68    uint8_t antibandingMode;
69    uint8_t sceneMode;
70
71    enum flashMode_t {
72        FLASH_MODE_OFF = 0,
73        FLASH_MODE_AUTO,
74        FLASH_MODE_ON,
75        FLASH_MODE_TORCH,
76        FLASH_MODE_RED_EYE = ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE,
77        FLASH_MODE_INVALID = -1
78    } flashMode;
79
80    enum focusMode_t {
81        FOCUS_MODE_AUTO = ANDROID_CONTROL_AF_MODE_AUTO,
82        FOCUS_MODE_MACRO = ANDROID_CONTROL_AF_MODE_MACRO,
83        FOCUS_MODE_CONTINUOUS_VIDEO = ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO,
84        FOCUS_MODE_CONTINUOUS_PICTURE = ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE,
85        FOCUS_MODE_EDOF = ANDROID_CONTROL_AF_MODE_EDOF,
86        FOCUS_MODE_INFINITY,
87        FOCUS_MODE_FIXED,
88        FOCUS_MODE_INVALID = -1
89    } focusMode;
90
91    uint8_t focusState; // Latest focus state from HAL
92
93    // For use with triggerAfWithAuto quirk
94    focusMode_t shadowFocusMode;
95
96    struct Area {
97        int left, top, right, bottom;
98        int weight;
99        Area() {}
100        Area(int left, int top, int right, int bottom, int weight):
101                left(left), top(top), right(right), bottom(bottom),
102                weight(weight) {}
103        bool isEmpty() const {
104            return (left == 0) && (top == 0) && (right == 0) && (bottom == 0);
105        }
106    };
107    Vector<Area> focusingAreas;
108
109    struct Size {
110        int32_t width;
111        int32_t height;
112    };
113
114    int32_t exposureCompensation;
115    bool autoExposureLock;
116    bool autoWhiteBalanceLock;
117
118    Vector<Area> meteringAreas;
119
120    int zoom;
121
122    int videoWidth, videoHeight;
123
124    bool recordingHint;
125    bool videoStabilization;
126
127    enum lightFxMode_t {
128        LIGHTFX_NONE = 0,
129        LIGHTFX_LOWLIGHT,
130        LIGHTFX_HDR
131    } lightFx;
132
133    CameraParameters params;
134    String8 paramsFlattened;
135
136    // These parameters are also part of the camera API-visible state, but not
137    // directly listed in Camera.Parameters
138    bool storeMetadataInBuffers;
139    bool playShutterSound;
140    bool enableFaceDetect;
141
142    bool enableFocusMoveMessages;
143    int afTriggerCounter;
144    int afStateCounter;
145    int currentAfTriggerId;
146    bool afInMotion;
147
148    int precaptureTriggerCounter;
149
150    int takePictureCounter;
151
152    uint32_t previewCallbackFlags;
153    bool previewCallbackOneShot;
154    bool previewCallbackSurface;
155
156    bool zslMode;
157
158    // Overall camera state
159    enum State {
160        DISCONNECTED,
161        STOPPED,
162        WAITING_FOR_PREVIEW_WINDOW,
163        PREVIEW,
164        RECORD,
165        STILL_CAPTURE,
166        VIDEO_SNAPSHOT
167    } state;
168
169    // Number of zoom steps to simulate
170    static const unsigned int NUM_ZOOM_STEPS = 100;
171    // Max preview size allowed
172    static const unsigned int MAX_PREVIEW_WIDTH = 1920;
173    static const unsigned int MAX_PREVIEW_HEIGHT = 1080;
174    // Aspect ratio tolerance
175    static const float ASPECT_RATIO_TOLERANCE = 0.001;
176
177    // Full static camera info, object owned by someone else, such as
178    // Camera2Device.
179    const CameraMetadata *info;
180
181    // Fast-access static device information; this is a subset of the
182    // information available through the staticInfo() method, used for
183    // frequently-accessed values or values that have to be calculated from the
184    // static information.
185    struct DeviceInfo {
186        int32_t arrayWidth;
187        int32_t arrayHeight;
188        int32_t bestStillCaptureFpsRange[2];
189        uint8_t bestFaceDetectMode;
190        int32_t maxFaces;
191        struct OverrideModes {
192            flashMode_t flashMode;
193            uint8_t     wbMode;
194            focusMode_t focusMode;
195            OverrideModes():
196                    flashMode(FLASH_MODE_INVALID),
197                    wbMode(ANDROID_CONTROL_AWB_MODE_OFF),
198                    focusMode(FOCUS_MODE_INVALID) {
199            }
200        };
201        DefaultKeyedVector<uint8_t, OverrideModes> sceneModeOverrides;
202        float minFocalLength;
203        bool useFlexibleYuv;
204    } fastInfo;
205
206    // Quirks information; these are short-lived flags to enable workarounds for
207    // incomplete HAL implementations
208    struct Quirks {
209        bool triggerAfWithAuto;
210        bool useZslFormat;
211        bool meteringCropRegion;
212        bool partialResults;
213    } quirks;
214
215    /**
216     * Parameter manipulation and setup methods
217     */
218
219    Parameters(int cameraId, int cameraFacing);
220    ~Parameters();
221
222    // Sets up default parameters
223    status_t initialize(const CameraMetadata *info);
224
225    // Build fast-access device static info from static info
226    status_t buildFastInfo();
227    // Query for quirks from static info
228    status_t buildQuirks();
229
230    // Get entry from camera static characteristics information. min/maxCount
231    // are used for error checking the number of values in the entry. 0 for
232    // max/minCount means to do no bounds check in that direction. In case of
233    // error, the entry data pointer is null and the count is 0.
234    camera_metadata_ro_entry_t staticInfo(uint32_t tag,
235            size_t minCount=0, size_t maxCount=0, bool required=true) const;
236
237    // Validate and update camera parameters based on new settings
238    status_t set(const String8 &paramString);
239
240    // Retrieve the current settings
241    String8 get() const;
242
243    // Update passed-in request for common parameters
244    status_t updateRequest(CameraMetadata *request) const;
245
246    // Add/update JPEG entries in metadata
247    status_t updateRequestJpeg(CameraMetadata *request) const;
248
249    // Calculate the crop region rectangle based on current stream sizes
250    struct CropRegion {
251        float left;
252        float top;
253        float width;
254        float height;
255
256        enum Outputs {
257            OUTPUT_PREVIEW         = 0x01,
258            OUTPUT_VIDEO           = 0x02,
259            OUTPUT_JPEG_THUMBNAIL  = 0x04,
260            OUTPUT_PICTURE         = 0x08,
261        };
262    };
263    CropRegion calculateCropRegion(CropRegion::Outputs outputs) const;
264
265    // Calculate the field of view of the high-resolution JPEG capture
266    status_t calculatePictureFovs(float *horizFov, float *vertFov) const;
267
268    // Static methods for debugging and converting between camera1 and camera2
269    // parameters
270
271    static const char *getStateName(State state);
272
273    static int formatStringToEnum(const char *format);
274    static const char *formatEnumToString(int format);
275
276    static int wbModeStringToEnum(const char *wbMode);
277    static const char* wbModeEnumToString(uint8_t wbMode);
278    static int effectModeStringToEnum(const char *effectMode);
279    static int abModeStringToEnum(const char *abMode);
280    static int sceneModeStringToEnum(const char *sceneMode);
281    static flashMode_t flashModeStringToEnum(const char *flashMode);
282    static const char* flashModeEnumToString(flashMode_t flashMode);
283    static focusMode_t focusModeStringToEnum(const char *focusMode);
284    static const char* focusModeEnumToString(focusMode_t focusMode);
285    static lightFxMode_t lightFxStringToEnum(const char *lightFxMode);
286
287    static status_t parseAreas(const char *areasCStr,
288            Vector<Area> *areas);
289
290    enum AreaKind
291    {
292        AREA_KIND_FOCUS,
293        AREA_KIND_METERING
294    };
295    status_t validateAreas(const Vector<Area> &areas,
296                                  size_t maxRegions,
297                                  AreaKind areaKind) const;
298    static bool boolFromString(const char *boolStr);
299
300    // Map from camera orientation + facing to gralloc transform enum
301    static int degToTransform(int degrees, bool mirror);
302
303    // API specifies FPS ranges are done in fixed point integer, with LSB = 0.001.
304    // Note that this doesn't apply to the (deprecated) single FPS value.
305    static const int kFpsToApiScale = 1000;
306
307    // Transform between (-1000,-1000)-(1000,1000) normalized coords from camera
308    // API and HAL2 (0,0)-(activePixelArray.width/height) coordinates
309    int arrayXToNormalized(int width) const;
310    int arrayYToNormalized(int height) const;
311    int normalizedXToArray(int x) const;
312    int normalizedYToArray(int y) const;
313
314    struct Range {
315        int min;
316        int max;
317    };
318
319    int32_t fpsFromRange(int32_t min, int32_t max) const;
320
321private:
322
323    // Convert between HAL2 sensor array coordinates and
324    // viewfinder crop-region relative array coordinates
325    int cropXToArray(int x) const;
326    int cropYToArray(int y) const;
327    int arrayXToCrop(int x) const;
328    int arrayYToCrop(int y) const;
329
330    // Convert between viewfinder crop-region relative array coordinates
331    // and camera API (-1000,1000)-(1000,1000) normalized coords
332    int cropXToNormalized(int x) const;
333    int cropYToNormalized(int y) const;
334    int normalizedXToCrop(int x) const;
335    int normalizedYToCrop(int y) const;
336
337    Vector<Size> availablePreviewSizes;
338    // Get size list (that are no larger than limit) from static metadata.
339    status_t getFilteredPreviewSizes(Size limit, Vector<Size> *sizes);
340    // Get max size (from the size array) that matches the given aspect ratio.
341    Size getMaxSizeForRatio(float ratio, const int32_t* sizeArray, size_t count);
342};
343
344// This class encapsulates the Parameters class so that it can only be accessed
345// by constructing a Lock object, which locks the SharedParameter's mutex.
346class SharedParameters {
347  public:
348    SharedParameters(int cameraId, int cameraFacing):
349            mParameters(cameraId, cameraFacing) {
350    }
351
352    template<typename S, typename P>
353    class BaseLock {
354      public:
355        BaseLock(S &p):
356                mParameters(p.mParameters),
357                mSharedParameters(p) {
358            mSharedParameters.mLock.lock();
359        }
360
361        ~BaseLock() {
362            mSharedParameters.mLock.unlock();
363        }
364        P &mParameters;
365      private:
366        // Disallow copying, default construction
367        BaseLock();
368        BaseLock(const BaseLock &);
369        BaseLock &operator=(const BaseLock &);
370        S &mSharedParameters;
371    };
372    typedef BaseLock<SharedParameters, Parameters> Lock;
373    typedef BaseLock<const SharedParameters, const Parameters> ReadLock;
374
375    // Access static info, read-only and immutable, so no lock needed
376    camera_metadata_ro_entry_t staticInfo(uint32_t tag,
377            size_t minCount=0, size_t maxCount=0) const {
378        return mParameters.staticInfo(tag, minCount, maxCount);
379    }
380
381    // Only use for dumping or other debugging
382    const Parameters &unsafeAccess() {
383        return mParameters;
384    }
385  private:
386    Parameters mParameters;
387    mutable Mutex mLock;
388};
389
390
391}; // namespace camera2
392}; // namespace android
393
394#endif
395