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