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