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