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