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