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