• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/Compat.h>
23 #include <utils/Errors.h>
24 #include <utils/KeyedVector.h>
25 #include <utils/Mutex.h>
26 #include <utils/String8.h>
27 #include <utils/Vector.h>
28 
29 #include <camera/CameraParameters.h>
30 #include <camera/CameraParameters2.h>
31 #include <camera/CameraMetadata.h>
32 
33 #include "common/CameraDeviceBase.h"
34 
35 namespace android {
36 namespace camera2 {
37 
38 /**
39  * Current camera state; this is the full state of the Camera under the old
40  * camera API (contents of the CameraParameters2 object in a more-efficient
41  * format, plus other state). The enum values are mostly based off the
42  * corresponding camera2 enums, not the camera1 strings. A few are defined here
43  * if they don't cleanly map to camera2 values.
44  */
45 struct Parameters {
46     /**
47      * Parameters and other state
48      */
49     int cameraId;
50     int cameraFacing;
51 
52     int previewWidth, previewHeight;
53     int32_t previewFpsRange[2];
54     int previewFormat;
55 
56     int previewTransform; // set by CAMERA_CMD_SET_DISPLAY_ORIENTATION
57 
58     int pictureWidth, pictureHeight;
59     // Store the picture size before they are overridden by video snapshot
60     int pictureWidthLastSet, pictureHeightLastSet;
61     bool pictureSizeOverriden;
62 
63     int32_t jpegThumbSize[2];
64     uint8_t jpegQuality, jpegThumbQuality;
65     int32_t jpegRotation;
66 
67     bool gpsEnabled;
68     double gpsCoordinates[3];
69     int64_t gpsTimestamp;
70     String8 gpsProcessingMethod;
71 
72     uint8_t wbMode;
73     uint8_t effectMode;
74     uint8_t antibandingMode;
75     uint8_t sceneMode;
76 
77     enum flashMode_t {
78         FLASH_MODE_OFF = 0,
79         FLASH_MODE_AUTO,
80         FLASH_MODE_ON,
81         FLASH_MODE_TORCH,
82         FLASH_MODE_RED_EYE = ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE,
83         FLASH_MODE_INVALID = -1
84     } flashMode;
85 
86     enum focusMode_t {
87         FOCUS_MODE_AUTO = ANDROID_CONTROL_AF_MODE_AUTO,
88         FOCUS_MODE_MACRO = ANDROID_CONTROL_AF_MODE_MACRO,
89         FOCUS_MODE_CONTINUOUS_VIDEO = ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO,
90         FOCUS_MODE_CONTINUOUS_PICTURE = ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE,
91         FOCUS_MODE_EDOF = ANDROID_CONTROL_AF_MODE_EDOF,
92         FOCUS_MODE_INFINITY,
93         FOCUS_MODE_FIXED,
94         FOCUS_MODE_INVALID = -1
95     } focusMode;
96 
97     uint8_t focusState; // Latest focus state from HAL
98 
99     // For use with triggerAfWithAuto quirk
100     focusMode_t shadowFocusMode;
101 
102     struct Area {
103         int left, top, right, bottom;
104         int weight;
AreaParameters::Area105         Area() {}
AreaParameters::Area106         Area(int left, int top, int right, int bottom, int weight):
107                 left(left), top(top), right(right), bottom(bottom),
108                 weight(weight) {}
isEmptyParameters::Area109         bool isEmpty() const {
110             return (left == 0) && (top == 0) && (right == 0) && (bottom == 0);
111         }
112     };
113     Vector<Area> focusingAreas;
114 
115     struct Size {
116         int32_t width;
117         int32_t height;
118     };
119 
120     struct FpsRange {
121         int32_t low;
122         int32_t high;
123     };
124 
125     uint8_t aeState; //latest AE state from Hal
126     int32_t exposureCompensation;
127     bool autoExposureLock;
128     bool autoExposureLockAvailable;
129     bool autoWhiteBalanceLock;
130     bool autoWhiteBalanceLockAvailable;
131 
132     // 3A region types, for use with ANDROID_CONTROL_MAX_REGIONS
133     enum region_t {
134         REGION_AE = 0,
135         REGION_AWB,
136         REGION_AF,
137         NUM_REGION // Number of region types
138     } region;
139 
140     Vector<Area> meteringAreas;
141 
142     int zoom;
143     bool zoomAvailable;
144 
145     int videoWidth, videoHeight, videoFormat;
146     android_dataspace videoDataSpace;
147 
148     bool recordingHint;
149     bool videoStabilization;
150 
151     CameraParameters2 params;
152     String8 paramsFlattened;
153 
154     // These parameters are also part of the camera API-visible state, but not
155     // directly listed in Camera.Parameters
156     // One of ICamera::VIDEO_BUFFER_MODE_*
157     int32_t videoBufferMode;
158     bool playShutterSound;
159     bool enableFaceDetect;
160 
161     bool enableFocusMoveMessages;
162     int afTriggerCounter;
163     int afStateCounter;
164     int currentAfTriggerId;
165     bool afInMotion;
166 
167     int precaptureTriggerCounter;
168 
169     int takePictureCounter;
170 
171     uint32_t previewCallbackFlags;
172     bool previewCallbackOneShot;
173     bool previewCallbackSurface;
174 
175     bool allowZslMode;
176     // Whether the jpeg stream is slower than 30FPS and can slow down preview.
177     // When slowJpegMode is true, allowZslMode must be false to avoid slowing down preview.
178     bool slowJpegMode;
179     // Whether ZSL reprocess is supported by the device.
180     bool isZslReprocessPresent;
181     // Whether the device supports enableZsl.
182     bool isDeviceZslSupported;
183     // Whether the device supports geometric distortion correction
184     bool isDistortionCorrectionSupported;
185     // Whether slowJpegMode is forced regardless of jpeg stream FPS
186     bool isSlowJpegModeForced;
187 
188     // Overall camera state
189     enum State {
190         DISCONNECTED,
191         STOPPED,
192         WAITING_FOR_PREVIEW_WINDOW,
193         PREVIEW,
194         RECORD,
195         STILL_CAPTURE,
196         VIDEO_SNAPSHOT
197     } state;
198 
199     // Number of zoom steps to simulate
200     static const unsigned int NUM_ZOOM_STEPS = 100;
201     // Max preview size allowed
202     // This is set to a 1:1 value to allow for any aspect ratio that has
203     // a max long side of 1920 pixels
204     static const unsigned int MAX_PREVIEW_WIDTH = 1920;
205     static const unsigned int MAX_PREVIEW_HEIGHT = 1920;
206     // Initial max preview/recording size bound
207     static const int MAX_INITIAL_PREVIEW_WIDTH = 1920;
208     static const int MAX_INITIAL_PREVIEW_HEIGHT = 1080;
209     // Aspect ratio tolerance
210     static const CONSTEXPR float ASPECT_RATIO_TOLERANCE = 0.01;
211     // Threshold for slow jpeg mode
212     static const int64_t kSlowJpegModeThreshold = 33400000LL; // 33.4 ms
213     // Margin for checking FPS
214     static const int32_t FPS_MARGIN = 1;
215     // Max FPS for default parameters
216     static const int32_t MAX_DEFAULT_FPS = 30;
217     // Minimum FPS for a size to be listed in supported preview/video sizes
218     // Set to slightly less than 30.0 to have some tolerance margin
219     static constexpr double MIN_PREVIEW_RECORD_FPS = 29.97;
220     // Maximum frame duration for a size to be listed in supported preview/video sizes
221     static constexpr int64_t MAX_PREVIEW_RECORD_DURATION_NS = 1e9 / MIN_PREVIEW_RECORD_FPS;
222 
223     // Full static camera info, object owned by someone else, such as
224     // Camera2Device.
225     const CameraMetadata *info;
226 
227     // Fast-access static device information; this is a subset of the
228     // information available through the staticInfo() method, used for
229     // frequently-accessed values or values that have to be calculated from the
230     // static information.
231     struct DeviceInfo {
232         int32_t arrayWidth;
233         int32_t arrayHeight;
234         int32_t bestStillCaptureFpsRange[2];
235         uint8_t bestFaceDetectMode;
236         int32_t maxFaces;
237         struct OverrideModes {
238             flashMode_t flashMode;
239             uint8_t     wbMode;
240             focusMode_t focusMode;
OverrideModesParameters::DeviceInfo::OverrideModes241             OverrideModes():
242                     flashMode(FLASH_MODE_INVALID),
243                     wbMode(ANDROID_CONTROL_AWB_MODE_OFF),
244                     focusMode(FOCUS_MODE_INVALID) {
245             }
246         };
247         DefaultKeyedVector<uint8_t, OverrideModes> sceneModeOverrides;
248         bool isExternalCamera;
249         float defaultFocalLength;
250         bool useFlexibleYuv;
251         Size maxJpegSize;
252         Size maxZslSize;
253         Size usedZslSize;
254         bool supportsPreferredConfigs;
255     } fastInfo;
256 
257     // Quirks information; these are short-lived flags to enable workarounds for
258     // incomplete HAL implementations
259     struct Quirks {
260         bool triggerAfWithAuto;
261         bool useZslFormat;
262         bool meteringCropRegion;
263         bool partialResults;
264     } quirks;
265 
266     /**
267      * Parameter manipulation and setup methods
268      */
269 
270     Parameters(int cameraId, int cameraFacing);
271     ~Parameters();
272 
273     // Sets up default parameters
274     status_t initialize(CameraDeviceBase *device);
275 
276     // Build fast-access device static info from static info
277     status_t buildFastInfo(CameraDeviceBase *device);
278     // Query for quirks from static info
279     status_t buildQuirks();
280 
281     // Get entry from camera static characteristics information. min/maxCount
282     // are used for error checking the number of values in the entry. 0 for
283     // max/minCount means to do no bounds check in that direction. In case of
284     // error, the entry data pointer is null and the count is 0.
285     camera_metadata_ro_entry_t staticInfo(uint32_t tag,
286             size_t minCount=0, size_t maxCount=0, bool required=true) const;
287 
288     // Validate and update camera parameters based on new settings
289     status_t set(const String8 &paramString);
290 
291     // Retrieve the current settings
292     String8 get() const;
293 
294     // Update passed-in request for common parameters
295     status_t updateRequest(CameraMetadata *request) const;
296 
297     // Add/update JPEG entries in metadata
298     status_t updateRequestJpeg(CameraMetadata *request) const;
299 
300     /* Helper functions to override jpeg size for video snapshot */
301     // Override jpeg size by video size. Called during startRecording.
302     status_t overrideJpegSizeByVideoSize();
303     // Recover overridden jpeg size.  Called during stopRecording.
304     status_t recoverOverriddenJpegSize();
305     // if video snapshot size is currently overridden
306     bool isJpegSizeOverridden();
307     // whether zero shutter lag should be used for non-recording operation
308     bool useZeroShutterLag() const;
309 
310     // Get default focal length
311     status_t getDefaultFocalLength(CameraDeviceBase *camera);
312 
313     // Calculate the crop region rectangle, either tightly about the preview
314     // resolution, or a region just based on the active array; both take
315     // into account the current zoom level.
316     struct CropRegion {
317         float left;
318         float top;
319         float width;
320         float height;
321     };
322     CropRegion calculateCropRegion(bool previewOnly) const;
323 
324     // Calculate the field of view of the high-resolution JPEG capture
325     status_t calculatePictureFovs(float *horizFov, float *vertFov) const;
326 
327     // Static methods for debugging and converting between camera1 and camera2
328     // parameters
329 
330     static const char *getStateName(State state);
331 
332     static int formatStringToEnum(const char *format);
333     static const char *formatEnumToString(int format);
334 
335     static int wbModeStringToEnum(const char *wbMode);
336     static const char* wbModeEnumToString(uint8_t wbMode);
337     static int effectModeStringToEnum(const char *effectMode);
338     static int abModeStringToEnum(const char *abMode);
339     static int sceneModeStringToEnum(const char *sceneMode, uint8_t defaultScene);
340     static flashMode_t flashModeStringToEnum(const char *flashMode);
341     static const char* flashModeEnumToString(flashMode_t flashMode);
342     static focusMode_t focusModeStringToEnum(const char *focusMode);
343     static const char* focusModeEnumToString(focusMode_t focusMode);
344 
345     static status_t parseAreas(const char *areasCStr,
346             Vector<Area> *areas);
347 
348     enum AreaKind
349     {
350         AREA_KIND_FOCUS,
351         AREA_KIND_METERING
352     };
353     status_t validateAreas(const Vector<Area> &areas,
354                                   size_t maxRegions,
355                                   AreaKind areaKind) const;
356     static bool boolFromString(const char *boolStr);
357 
358     // Map from camera orientation + facing to gralloc transform enum
359     static int degToTransform(int degrees, bool mirror);
360 
361     // API specifies FPS ranges are done in fixed point integer, with LSB = 0.001.
362     // Note that this doesn't apply to the (deprecated) single FPS value.
363     static const int kFpsToApiScale = 1000;
364 
365     // Transform from (-1000,-1000)-(1000,1000) normalized coords from camera
366     // API to HAL3 (0,0)-(activePixelArray.width/height) coordinates
367     int normalizedXToArray(int x) const;
368     int normalizedYToArray(int y) const;
369 
370     // Transform from HAL3 (0,0)-(activePixelArray.width/height) coordinates to
371     // (-1000,-1000)-(1000,1000) normalized coordinates given a scaler crop
372     // region.
373     int arrayXToNormalizedWithCrop(int x, const CropRegion &scalerCrop) const;
374     int arrayYToNormalizedWithCrop(int y, const CropRegion &scalerCrop) const;
375 
376     struct Range {
377         int min;
378         int max;
379     };
380 
381     int32_t fpsFromRange(int32_t min, int32_t max) const;
382 
383 private:
384 
385     // Convert from viewfinder crop-region relative array coordinates
386     // to HAL3 sensor array coordinates
387     int cropXToArray(int x) const;
388     int cropYToArray(int y) const;
389 
390     // Convert from camera API (-1000,1000)-(1000,1000) normalized coords
391     // to viewfinder crop-region relative array coordinates
392     int normalizedXToCrop(int x) const;
393     int normalizedYToCrop(int y) const;
394 
395     // Given a scaler crop region, calculate preview crop region based on
396     // preview aspect ratio.
397     CropRegion calculatePreviewCrop(const CropRegion &scalerCrop) const;
398 
399     Vector<Size> availablePreviewSizes;
400     Vector<Size> availableVideoSizes;
401     // Get size list (that fall within lower/upper bounds) from static metadata.
402     // This method filtered size with minFrameDuration < MAX_PREVIEW_RECORD_DURATION_NS
403     status_t getFilteredSizes(const Size &lower, const Size &upper,
404             Vector<Size> *sizes);
405     // Get max size (from the size array) that matches the given aspect ratio.
406     Size getMaxSizeForRatio(float ratio, const int32_t* sizeArray, size_t count);
407 
408     // Helper function for overriding jpeg size for video snapshot
409     // Check if overridden jpeg size needs to be updated after Parameters::set.
410     // The behavior of this function is tailored to the implementation of Parameters::set.
411     // Do not use this function for other purpose.
412     status_t updateOverriddenJpegSize();
413 
414     struct StreamConfiguration {
415         int32_t format;
416         int32_t width;
417         int32_t height;
418         int32_t isInput;
419     };
420 
421     // Helper function extract available stream configuration
422     // Only valid since device HAL version 3.2
423     // returns an empty Vector if device HAL version does support it
424     Vector<StreamConfiguration> getStreamConfigurations();
425 
426     // Helper function to extract the suggested stream configurations
427     Vector<StreamConfiguration> getPreferredStreamConfigurations(int32_t usecaseId) const;
428 
429     // Helper function to get minimum frame duration for a jpeg size
430     // return -1 if input jpeg size cannot be found in supported size list
431     int64_t getJpegStreamMinFrameDurationNs(Parameters::Size size);
432 
433     // Helper function to get minimum frame duration for a
434     // IMPLEMENTATION_DEFINED stream of size 'size'
435     // return -1 if input size cannot be found in supported size list
436     int64_t getZslStreamMinFrameDurationNs(Parameters::Size size);
437 
438     // Helper function to get minimum frame duration for a size/format combination
439     // return -1 if input size/format combination cannot be found.
440     int64_t getMinFrameDurationNs(Parameters::Size size, int format);
441 
442     // Helper function to check if a given fps is supported by all the sizes with
443     // the same format.
444     // return true if the device doesn't support min frame duration metadata tag.
445     bool isFpsSupported(const Vector<Size> &size, int format, int32_t fps);
446 
447     // Helper function to get non-duplicated available output formats
448     SortedVector<int32_t> getAvailableOutputFormats();
449     // Helper function to get available output jpeg sizes
450     Vector<Size> getAvailableJpegSizes();
451     // Helper function to get maximum size in input Size vector.
452     // The maximum size is defined by comparing width first, when width ties comparing height.
453     Size getMaxSize(const Vector<Size>& sizes);
454 
455     // Helper function to filter and sort suggested sizes
456     Vector<Parameters::Size> getPreferredFilteredSizes(int32_t usecaseId, int32_t format) const;
457     // Helper function to get the suggested jpeg sizes
458     Vector<Size> getPreferredJpegSizes() const;
459     // Helper function to get the suggested preview sizes
460     Vector<Size> getPreferredPreviewSizes() const;
461     // Helper function to get the suggested video sizes
462     Vector<Size> getPreferredVideoSizes() const;
463 
464     uint8_t mDefaultSceneMode;
465 };
466 
467 // This class encapsulates the Parameters class so that it can only be accessed
468 // by constructing a Lock object, which locks the SharedParameter's mutex.
469 class SharedParameters {
470   public:
SharedParameters(int cameraId,int cameraFacing)471     SharedParameters(int cameraId, int cameraFacing):
472             mParameters(cameraId, cameraFacing) {
473     }
474 
475     template<typename S, typename P>
476     class BaseLock {
477       public:
BaseLock(S & p)478         explicit BaseLock(S &p):
479                 mParameters(p.mParameters),
480                 mSharedParameters(p) {
481             mSharedParameters.mLock.lock();
482         }
483 
~BaseLock()484         ~BaseLock() {
485             mSharedParameters.mLock.unlock();
486         }
487         P &mParameters;
488       private:
489         // Disallow copying, default construction
490         BaseLock();
491         BaseLock(const BaseLock &);
492         BaseLock &operator=(const BaseLock &);
493         S &mSharedParameters;
494     };
495     typedef BaseLock<SharedParameters, Parameters> Lock;
496     typedef BaseLock<const SharedParameters, const Parameters> ReadLock;
497 
498     // Access static info, read-only and immutable, so no lock needed
499     camera_metadata_ro_entry_t staticInfo(uint32_t tag,
500             size_t minCount=0, size_t maxCount=0) const {
501         return mParameters.staticInfo(tag, minCount, maxCount);
502     }
503 
504     // Only use for dumping or other debugging
unsafeAccess()505     const Parameters &unsafeAccess() {
506         return mParameters;
507     }
508   private:
509     Parameters mParameters;
510     mutable Mutex mLock;
511 };
512 
513 
514 }; // namespace camera2
515 }; // namespace android
516 
517 #endif
518