• 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     bool videoStabilizationOnSupported = false;
151 
152     CameraParameters2 params;
153     String8 paramsFlattened;
154 
155     // These parameters are also part of the camera API-visible state, but not
156     // directly listed in Camera.Parameters
157     // One of ICamera::VIDEO_BUFFER_MODE_*
158     int32_t videoBufferMode;
159     bool playShutterSound;
160     bool enableFaceDetect;
161 
162     bool enableFocusMoveMessages;
163     int afTriggerCounter;
164     int afStateCounter;
165     int currentAfTriggerId;
166     bool afInMotion;
167 
168     int precaptureTriggerCounter;
169 
170     int takePictureCounter;
171 
172     uint32_t previewCallbackFlags;
173     bool previewCallbackOneShot;
174     bool previewCallbackSurface;
175 
176     bool allowZslMode;
177     // Whether the jpeg stream is slower than 30FPS and can slow down preview.
178     // When slowJpegMode is true, allowZslMode must be false to avoid slowing down preview.
179     bool slowJpegMode;
180     // Whether ZSL reprocess is supported by the device.
181     bool isZslReprocessPresent;
182     // Whether the device supports enableZsl.
183     bool isDeviceZslSupported;
184     // Whether the device supports geometric distortion correction
185     bool isDistortionCorrectionSupported;
186     // Whether slowJpegMode is forced regardless of jpeg stream FPS
187     bool isSlowJpegModeForced;
188 
189     // Overall camera state
190     enum State {
191         DISCONNECTED,
192         STOPPED,
193         WAITING_FOR_PREVIEW_WINDOW,
194         PREVIEW,
195         RECORD,
196         STILL_CAPTURE,
197         VIDEO_SNAPSHOT
198     } state;
199 
200     // Number of zoom steps to simulate
201     static const unsigned int NUM_ZOOM_STEPS = 100;
202     // Max preview size allowed
203     // This is set to a 1:1 value to allow for any aspect ratio that has
204     // a max long side of 1920 pixels
205     static const unsigned int MAX_PREVIEW_WIDTH = 1920;
206     static const unsigned int MAX_PREVIEW_HEIGHT = 1920;
207     // Initial max preview/recording size bound
208     static const int MAX_INITIAL_PREVIEW_WIDTH = 1920;
209     static const int MAX_INITIAL_PREVIEW_HEIGHT = 1080;
210     // Aspect ratio tolerance
211     static const CONSTEXPR float ASPECT_RATIO_TOLERANCE = 0.01;
212     // Threshold for slow jpeg mode
213     static const int64_t kSlowJpegModeThreshold = 33400000LL; // 33.4 ms
214     // Margin for checking FPS
215     static const int32_t FPS_MARGIN = 1;
216     // Max FPS for default parameters
217     static const int32_t MAX_DEFAULT_FPS = 30;
218     // Minimum FPS for a size to be listed in supported preview/video sizes
219     // Set to slightly less than 30.0 to have some tolerance margin
220     static constexpr double MIN_PREVIEW_RECORD_FPS = 29.97;
221     // Maximum frame duration for a size to be listed in supported preview/video sizes
222     static constexpr int64_t MAX_PREVIEW_RECORD_DURATION_NS = 1e9 / MIN_PREVIEW_RECORD_FPS;
223 
224     // Full static camera info, object owned by someone else, such as
225     // Camera2Device.
226     const CameraMetadata *info;
227 
228     // Fast-access static device information; this is a subset of the
229     // information available through the staticInfo() method, used for
230     // frequently-accessed values or values that have to be calculated from the
231     // static information.
232     struct DeviceInfo {
233         int32_t arrayWidth;
234         int32_t arrayHeight;
235         int32_t bestStillCaptureFpsRange[2];
236         uint8_t bestFaceDetectMode;
237         int32_t maxFaces;
238         struct OverrideModes {
239             flashMode_t flashMode;
240             uint8_t     wbMode;
241             focusMode_t focusMode;
OverrideModesParameters::DeviceInfo::OverrideModes242             OverrideModes():
243                     flashMode(FLASH_MODE_INVALID),
244                     wbMode(ANDROID_CONTROL_AWB_MODE_OFF),
245                     focusMode(FOCUS_MODE_INVALID) {
246             }
247         };
248         DefaultKeyedVector<uint8_t, OverrideModes> sceneModeOverrides;
249         bool isExternalCamera;
250         float defaultFocalLength;
251         bool useFlexibleYuv;
252         Size maxJpegSize;
253         Size maxZslSize;
254         Size usedZslSize;
255         bool supportsPreferredConfigs;
256     } fastInfo;
257 
258     // Quirks information; these are short-lived flags to enable workarounds for
259     // incomplete HAL implementations
260     struct Quirks {
261         bool triggerAfWithAuto;
262         bool useZslFormat;
263         bool meteringCropRegion;
264         bool partialResults;
265     } quirks;
266 
267     /**
268      * Parameter manipulation and setup methods
269      */
270 
271     Parameters(int cameraId, int cameraFacing);
272     ~Parameters();
273 
274     // Sets up default parameters
275     status_t initialize(CameraDeviceBase *device);
276 
277     // Build fast-access device static info from static info
278     status_t buildFastInfo(CameraDeviceBase *device);
279     // Query for quirks from static info
280     status_t buildQuirks();
281 
282     // Get entry from camera static characteristics information. min/maxCount
283     // are used for error checking the number of values in the entry. 0 for
284     // max/minCount means to do no bounds check in that direction. In case of
285     // error, the entry data pointer is null and the count is 0.
286     camera_metadata_ro_entry_t staticInfo(uint32_t tag,
287             size_t minCount=0, size_t maxCount=0, bool required=true) const;
288 
289     // Validate and update camera parameters based on new settings
290     status_t set(const String8 &paramString);
291 
292     // Retrieve the current settings
293     String8 get() const;
294 
295     // Update passed-in request for common parameters
296     status_t updateRequest(CameraMetadata *request) const;
297 
298     // Add/update JPEG entries in metadata
299     status_t updateRequestJpeg(CameraMetadata *request) const;
300 
301     /* Helper functions to override jpeg size for video snapshot */
302     // Override jpeg size by video size. Called during startRecording.
303     status_t overrideJpegSizeByVideoSize();
304     // Recover overridden jpeg size.  Called during stopRecording.
305     status_t recoverOverriddenJpegSize();
306     // if video snapshot size is currently overridden
307     bool isJpegSizeOverridden();
308     // whether zero shutter lag should be used for non-recording operation
309     bool useZeroShutterLag() const;
310 
311     // Get default focal length
312     status_t getDefaultFocalLength(CameraDeviceBase *camera);
313 
314     // Calculate the crop region rectangle, either tightly about the preview
315     // resolution, or a region just based on the active array; both take
316     // into account the current zoom level.
317     struct CropRegion {
318         float left;
319         float top;
320         float width;
321         float height;
322     };
323     CropRegion calculateCropRegion(bool previewOnly) const;
324 
325     // Calculate the field of view of the high-resolution JPEG capture
326     status_t calculatePictureFovs(float *horizFov, float *vertFov) const;
327 
328     // Static methods for debugging and converting between camera1 and camera2
329     // parameters
330 
331     static const char *getStateName(State state);
332 
333     static int formatStringToEnum(const char *format);
334     static const char *formatEnumToString(int format);
335 
336     static int wbModeStringToEnum(const char *wbMode);
337     static const char* wbModeEnumToString(uint8_t wbMode);
338     static int effectModeStringToEnum(const char *effectMode);
339     static int abModeStringToEnum(const char *abMode);
340     static int sceneModeStringToEnum(const char *sceneMode, uint8_t defaultScene);
341     static flashMode_t flashModeStringToEnum(const char *flashMode);
342     static const char* flashModeEnumToString(flashMode_t flashMode);
343     static focusMode_t focusModeStringToEnum(const char *focusMode);
344     static const char* focusModeEnumToString(focusMode_t focusMode);
345 
346     static status_t parseAreas(const char *areasCStr,
347             Vector<Area> *areas);
348 
349     enum AreaKind
350     {
351         AREA_KIND_FOCUS,
352         AREA_KIND_METERING
353     };
354     status_t validateAreas(const Vector<Area> &areas,
355                                   size_t maxRegions,
356                                   AreaKind areaKind) const;
357     static bool boolFromString(const char *boolStr);
358 
359     // Map from camera orientation + facing to gralloc transform enum
360     static int degToTransform(int degrees, bool mirror);
361 
362     // API specifies FPS ranges are done in fixed point integer, with LSB = 0.001.
363     // Note that this doesn't apply to the (deprecated) single FPS value.
364     static const int kFpsToApiScale = 1000;
365 
366     // Transform from (-1000,-1000)-(1000,1000) normalized coords from camera
367     // API to HAL3 (0,0)-(activePixelArray.width/height) coordinates
368     int normalizedXToArray(int x) const;
369     int normalizedYToArray(int y) const;
370 
371     // Transform from HAL3 (0,0)-(activePixelArray.width/height) coordinates to
372     // (-1000,-1000)-(1000,1000) normalized coordinates given a scaler crop
373     // region.
374     int arrayXToNormalizedWithCrop(int x, const CropRegion &scalerCrop) const;
375     int arrayYToNormalizedWithCrop(int y, const CropRegion &scalerCrop) const;
376 
377     struct Range {
378         int min;
379         int max;
380     };
381 
382     int32_t fpsFromRange(int32_t min, int32_t max) const;
383 
384 private:
385 
386     // Convert from viewfinder crop-region relative array coordinates
387     // to HAL3 sensor array coordinates
388     int cropXToArray(int x) const;
389     int cropYToArray(int y) const;
390 
391     // Convert from camera API (-1000,1000)-(1000,1000) normalized coords
392     // to viewfinder crop-region relative array coordinates
393     int normalizedXToCrop(int x) const;
394     int normalizedYToCrop(int y) const;
395 
396     // Given a scaler crop region, calculate preview crop region based on
397     // preview aspect ratio.
398     CropRegion calculatePreviewCrop(const CropRegion &scalerCrop) const;
399 
400     Vector<Size> availablePreviewSizes;
401     Vector<Size> availableVideoSizes;
402     // Get size list (that fall within lower/upper bounds) from static metadata.
403     // This method filtered size with minFrameDuration < MAX_PREVIEW_RECORD_DURATION_NS
404     status_t getFilteredSizes(const Size &lower, const Size &upper,
405             Vector<Size> *sizes);
406     // Get max size (from the size array) that matches the given aspect ratio.
407     Size getMaxSizeForRatio(float ratio, const int32_t* sizeArray, size_t count);
408 
409     // Helper function for overriding jpeg size for video snapshot
410     // Check if overridden jpeg size needs to be updated after Parameters::set.
411     // The behavior of this function is tailored to the implementation of Parameters::set.
412     // Do not use this function for other purpose.
413     status_t updateOverriddenJpegSize();
414 
415     struct StreamConfiguration {
416         int32_t format;
417         int32_t width;
418         int32_t height;
419         int32_t isInput;
420     };
421 
422     // Helper function extract available stream configuration
423     // Only valid since device HAL version 3.2
424     // returns an empty Vector if device HAL version does support it
425     Vector<StreamConfiguration> getStreamConfigurations();
426 
427     // Helper function to extract the suggested stream configurations
428     Vector<StreamConfiguration> getPreferredStreamConfigurations(int32_t usecaseId) const;
429 
430     // Helper function to get minimum frame duration for a jpeg size
431     // return -1 if input jpeg size cannot be found in supported size list
432     int64_t getJpegStreamMinFrameDurationNs(Parameters::Size size);
433 
434     // Helper function to get minimum frame duration for a
435     // IMPLEMENTATION_DEFINED stream of size 'size'
436     // return -1 if input size cannot be found in supported size list
437     int64_t getZslStreamMinFrameDurationNs(Parameters::Size size);
438 
439     // Helper function to get minimum frame duration for a size/format combination
440     // return -1 if input size/format combination cannot be found.
441     int64_t getMinFrameDurationNs(Parameters::Size size, int format);
442 
443     // Helper function to check if a given fps is supported by all the sizes with
444     // the same format.
445     // return true if the device doesn't support min frame duration metadata tag.
446     bool isFpsSupported(const Vector<Size> &size, int format, int32_t fps);
447 
448     // Helper function to get non-duplicated available output formats
449     SortedVector<int32_t> getAvailableOutputFormats();
450     // Helper function to get available output jpeg sizes
451     Vector<Size> getAvailableJpegSizes();
452     // Helper function to get maximum size in input Size vector.
453     // The maximum size is defined by comparing width first, when width ties comparing height.
454     Size getMaxSize(const Vector<Size>& sizes);
455 
456     // Helper function to filter and sort suggested sizes
457     Vector<Parameters::Size> getPreferredFilteredSizes(int32_t usecaseId, int32_t format) const;
458     // Helper function to get the suggested jpeg sizes
459     Vector<Size> getPreferredJpegSizes() const;
460     // Helper function to get the suggested preview sizes
461     Vector<Size> getPreferredPreviewSizes() const;
462     // Helper function to get the suggested video sizes
463     Vector<Size> getPreferredVideoSizes() const;
464 
465     uint8_t mDefaultSceneMode;
466 };
467 
468 // This class encapsulates the Parameters class so that it can only be accessed
469 // by constructing a Lock object, which locks the SharedParameter's mutex.
470 class SharedParameters {
471   public:
SharedParameters(int cameraId,int cameraFacing)472     SharedParameters(int cameraId, int cameraFacing):
473             mParameters(cameraId, cameraFacing) {
474     }
475 
476     template<typename S, typename P>
477     class BaseLock {
478       public:
BaseLock(S & p)479         explicit BaseLock(S &p):
480                 mParameters(p.mParameters),
481                 mSharedParameters(p) {
482             mSharedParameters.mLock.lock();
483         }
484 
~BaseLock()485         ~BaseLock() {
486             mSharedParameters.mLock.unlock();
487         }
488         P &mParameters;
489       private:
490         // Disallow copying, default construction
491         BaseLock();
492         BaseLock(const BaseLock &);
493         BaseLock &operator=(const BaseLock &);
494         S &mSharedParameters;
495     };
496     typedef BaseLock<SharedParameters, Parameters> Lock;
497     typedef BaseLock<const SharedParameters, const Parameters> ReadLock;
498 
499     // Access static info, read-only and immutable, so no lock needed
500     camera_metadata_ro_entry_t staticInfo(uint32_t tag,
501             size_t minCount=0, size_t maxCount=0) const {
502         return mParameters.staticInfo(tag, minCount, maxCount);
503     }
504 
505     // Only use for dumping or other debugging
unsafeAccess()506     const Parameters &unsafeAccess() {
507         return mParameters;
508     }
509   private:
510     Parameters mParameters;
511     mutable Mutex mLock;
512 };
513 
514 
515 }; // namespace camera2
516 }; // namespace android
517 
518 #endif
519