• 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 #define LOG_TAG "Camera2-Parameters"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 // #define LOG_NDEBUG 0
20 
21 #include <utils/Log.h>
22 #include <utils/Trace.h>
23 #include <utils/Vector.h>
24 #include <utils/SortedVector.h>
25 
26 #include <math.h>
27 #include <stdlib.h>
28 #include <cutils/properties.h>
29 
30 #include "Parameters.h"
31 #include "system/camera.h"
32 #include <android-base/properties.h>
33 #include <android/hardware/ICamera.h>
34 #include <media/MediaProfiles.h>
35 #include <media/mediarecorder.h>
36 
37 namespace android {
38 namespace camera2 {
39 
40 using android::camera3::CAMERA_TEMPLATE_PREVIEW;
41 
Parameters(int cameraId,int cameraFacing)42 Parameters::Parameters(int cameraId,
43         int cameraFacing) :
44         cameraId(cameraId),
45         cameraFacing(cameraFacing),
46         info(NULL),
47         mDefaultSceneMode(ANDROID_CONTROL_SCENE_MODE_DISABLED) {
48 }
49 
~Parameters()50 Parameters::~Parameters() {
51 }
52 
initialize(CameraDeviceBase * device)53 status_t Parameters::initialize(CameraDeviceBase *device) {
54     status_t res;
55     if (device == nullptr) {
56         ALOGE("%s: device is null!", __FUNCTION__);
57         return BAD_VALUE;
58     }
59 
60     const CameraMetadata& info = device->info();
61     if (info.entryCount() == 0) {
62         ALOGE("%s: No static information provided!", __FUNCTION__);
63         return BAD_VALUE;
64     }
65     Parameters::info = &info;
66 
67     res = buildFastInfo(device);
68     if (res != OK) return res;
69 
70     res = buildQuirks();
71     if (res != OK) return res;
72 
73     Size maxPreviewSize = { MAX_PREVIEW_WIDTH, MAX_PREVIEW_HEIGHT };
74     // Treat the H.264 max size as the max supported video size.
75     MediaProfiles *videoEncoderProfiles = MediaProfiles::getInstance();
76     Vector<video_encoder> encoders = videoEncoderProfiles->getVideoEncoders();
77     int32_t minVideoWidth = MAX_PREVIEW_WIDTH;
78     int32_t minVideoHeight = MAX_PREVIEW_HEIGHT;
79     int32_t maxVideoWidth = 0;
80     int32_t maxVideoHeight = 0;
81     for (size_t i = 0; i < encoders.size(); i++) {
82         int w0 = videoEncoderProfiles->getVideoEncoderParamByName(
83                 "enc.vid.width.min", encoders[i]);
84         int h0 = videoEncoderProfiles->getVideoEncoderParamByName(
85                 "enc.vid.height.min", encoders[i]);
86         int w1 = videoEncoderProfiles->getVideoEncoderParamByName(
87                 "enc.vid.width.max", encoders[i]);
88         int h1 = videoEncoderProfiles->getVideoEncoderParamByName(
89                 "enc.vid.height.max", encoders[i]);
90         // Assume the min size is 0 if it's not reported by encoder
91         if (w0 == -1) {
92             w0 = 0;
93         }
94         if (h0 == -1) {
95             h0 = 0;
96         }
97         // Treat width/height separately here to handle the case where different
98         // profile might report min/max size of different aspect ratio
99         if (w0 < minVideoWidth) {
100             minVideoWidth = w0;
101         }
102         if (h0 < minVideoHeight) {
103             minVideoHeight = h0;
104         }
105         if (w1 > maxVideoWidth) {
106             maxVideoWidth = w1;
107         }
108         if (h1 > maxVideoHeight) {
109             maxVideoHeight = h1;
110         }
111     }
112     // These are upper/lower bounds and may not be an actually valid video size
113     const Size VIDEO_SIZE_LOWER_BOUND = {minVideoWidth, minVideoHeight};
114     Size videoSizeUpperBound = {maxVideoWidth, maxVideoHeight};
115 
116     if (fastInfo.supportsPreferredConfigs) {
117         maxPreviewSize = getMaxSize(getPreferredPreviewSizes());
118         videoSizeUpperBound = getMaxSize(getPreferredVideoSizes());
119     }
120 
121     res = getFilteredSizes(Size{0, 0}, maxPreviewSize, &availablePreviewSizes);
122     if (res != OK) return res;
123     res = getFilteredSizes(
124         VIDEO_SIZE_LOWER_BOUND, videoSizeUpperBound, &availableVideoSizes);
125     if (res != OK) return res;
126 
127     // Select initial preview and video size that's under the initial bound and
128     // on the list of both preview and recording sizes
129     previewWidth = 0;
130     previewHeight = 0;
131     for (size_t i = 0 ; i < availablePreviewSizes.size(); i++) {
132         int newWidth = availablePreviewSizes[i].width;
133         int newHeight = availablePreviewSizes[i].height;
134         if (newWidth >= previewWidth && newHeight >= previewHeight &&
135                 newWidth <= MAX_INITIAL_PREVIEW_WIDTH &&
136                 newHeight <= MAX_INITIAL_PREVIEW_HEIGHT) {
137             for (size_t j = 0; j < availableVideoSizes.size(); j++) {
138                 if (availableVideoSizes[j].width == newWidth &&
139                         availableVideoSizes[j].height == newHeight) {
140                     previewWidth = newWidth;
141                     previewHeight = newHeight;
142                 }
143             }
144         }
145     }
146     if (previewWidth == 0) {
147         ALOGE("%s: No initial preview size can be found!", __FUNCTION__);
148         return BAD_VALUE;
149     }
150     videoWidth = previewWidth;
151     videoHeight = previewHeight;
152 
153     params.setPreviewSize(previewWidth, previewHeight);
154     params.setVideoSize(videoWidth, videoHeight);
155     params.set(CameraParameters::KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO,
156             String8::format("%dx%d",
157                     previewWidth, previewHeight));
158     {
159         String8 supportedPreviewSizes;
160         for (size_t i = 0; i < availablePreviewSizes.size(); i++) {
161             if (i != 0) supportedPreviewSizes += ",";
162             supportedPreviewSizes += String8::format("%dx%d",
163                     availablePreviewSizes[i].width,
164                     availablePreviewSizes[i].height);
165         }
166         ALOGV("Supported preview sizes are: %s", supportedPreviewSizes.string());
167         params.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES,
168                 supportedPreviewSizes);
169 
170         String8 supportedVideoSizes;
171         for (size_t i = 0; i < availableVideoSizes.size(); i++) {
172             if (i != 0) supportedVideoSizes += ",";
173             supportedVideoSizes += String8::format("%dx%d",
174                     availableVideoSizes[i].width,
175                     availableVideoSizes[i].height);
176         }
177         ALOGV("Supported video sizes are: %s", supportedVideoSizes.string());
178         params.set(CameraParameters::KEY_SUPPORTED_VIDEO_SIZES,
179                 supportedVideoSizes);
180     }
181 
182     camera_metadata_ro_entry_t availableFpsRanges =
183         staticInfo(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES, 2);
184     if (!availableFpsRanges.count) return NO_INIT;
185 
186     previewFormat = HAL_PIXEL_FORMAT_YCrCb_420_SP;
187     params.set(CameraParameters::KEY_PREVIEW_FORMAT,
188             formatEnumToString(previewFormat)); // NV21
189 
190     previewTransform = degToTransform(0,
191             cameraFacing == CAMERA_FACING_FRONT);
192 
193     {
194         String8 supportedPreviewFormats;
195         SortedVector<int32_t> outputFormats = getAvailableOutputFormats();
196         bool addComma = false;
197         for (size_t i=0; i < outputFormats.size(); i++) {
198             if (addComma) supportedPreviewFormats += ",";
199             addComma = true;
200             switch (outputFormats[i]) {
201             case HAL_PIXEL_FORMAT_YCbCr_422_SP:
202                 supportedPreviewFormats +=
203                     CameraParameters::PIXEL_FORMAT_YUV422SP;
204                 break;
205             case HAL_PIXEL_FORMAT_YCrCb_420_SP:
206                 supportedPreviewFormats +=
207                     CameraParameters::PIXEL_FORMAT_YUV420SP;
208                 break;
209             case HAL_PIXEL_FORMAT_YCbCr_422_I:
210                 supportedPreviewFormats +=
211                     CameraParameters::PIXEL_FORMAT_YUV422I;
212                 break;
213             case HAL_PIXEL_FORMAT_YV12:
214                 supportedPreviewFormats +=
215                     CameraParameters::PIXEL_FORMAT_YUV420P;
216                 break;
217             case HAL_PIXEL_FORMAT_RGB_565:
218                 supportedPreviewFormats +=
219                     CameraParameters::PIXEL_FORMAT_RGB565;
220                 break;
221             case HAL_PIXEL_FORMAT_RGBA_8888:
222                 supportedPreviewFormats +=
223                     CameraParameters::PIXEL_FORMAT_RGBA8888;
224                 break;
225             case HAL_PIXEL_FORMAT_YCbCr_420_888:
226                 // Flexible YUV allows both YV12 and NV21
227                 supportedPreviewFormats +=
228                     CameraParameters::PIXEL_FORMAT_YUV420P;
229                 supportedPreviewFormats += ",";
230                 supportedPreviewFormats +=
231                     CameraParameters::PIXEL_FORMAT_YUV420SP;
232                 break;
233             // Not advertizing JPEG, RAW16, etc, for preview formats
234             case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
235             case HAL_PIXEL_FORMAT_RAW16:
236             case HAL_PIXEL_FORMAT_BLOB:
237                 addComma = false;
238                 break;
239 
240             default:
241                 ALOGW("%s: Camera %d: Unknown preview format: %x",
242                         __FUNCTION__, cameraId, outputFormats[i]);
243                 addComma = false;
244                 break;
245             }
246         }
247         params.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS,
248                 supportedPreviewFormats);
249     }
250 
251     previewFpsRange[0] = fastInfo.bestStillCaptureFpsRange[0];
252     previewFpsRange[1] = fastInfo.bestStillCaptureFpsRange[1];
253 
254     // PREVIEW_FRAME_RATE / SUPPORTED_PREVIEW_FRAME_RATES are deprecated, but
255     // still have to do something reasonable for them
256 
257     // NOTE: Not scaled like FPS range values are.
258     int previewFps = fpsFromRange(previewFpsRange[0], previewFpsRange[1]);
259     params.set(CameraParameters::KEY_PREVIEW_FRAME_RATE,
260             previewFps);
261 
262     // PREVIEW_FPS_RANGE
263     // -- Order matters. Set range after single value to so that a roundtrip
264     //    of setParameters(getParameters()) would keep the FPS range in higher
265     //    order.
266     params.set(CameraParameters::KEY_PREVIEW_FPS_RANGE,
267             String8::format("%d,%d",
268                     previewFpsRange[0] * kFpsToApiScale,
269                     previewFpsRange[1] * kFpsToApiScale));
270 
271     {
272         String8 supportedPreviewFpsRange;
273         for (size_t i=0; i < availableFpsRanges.count; i += 2) {
274             if (!isFpsSupported(availablePreviewSizes,
275                 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, availableFpsRanges.data.i32[i+1])) {
276                 continue;
277             }
278             if (supportedPreviewFpsRange.length() > 0) {
279                 supportedPreviewFpsRange += ",";
280             }
281             supportedPreviewFpsRange += String8::format("(%d,%d)",
282                     availableFpsRanges.data.i32[i] * kFpsToApiScale,
283                     availableFpsRanges.data.i32[i+1] * kFpsToApiScale);
284         }
285         params.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE,
286                 supportedPreviewFpsRange);
287     }
288 
289     {
290         SortedVector<int32_t> sortedPreviewFrameRates;
291 
292         String8 supportedPreviewFrameRates;
293         for (size_t i=0; i < availableFpsRanges.count; i += 2) {
294             // from the [min, max] fps range use the max value
295             int fps = fpsFromRange(availableFpsRanges.data.i32[i],
296                                    availableFpsRanges.data.i32[i+1]);
297             if (!isFpsSupported(availablePreviewSizes,
298                     HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, fps)) {
299                 continue;
300             }
301             // de-dupe frame rates
302             if (sortedPreviewFrameRates.indexOf(fps) == NAME_NOT_FOUND) {
303                 sortedPreviewFrameRates.add(fps);
304             }
305             else {
306                 continue;
307             }
308 
309             if (sortedPreviewFrameRates.size() > 1) {
310                 supportedPreviewFrameRates += ",";
311             }
312 
313             supportedPreviewFrameRates += String8::format("%d",
314                     fps);
315 
316             ALOGV("%s: Supported preview frame rates: %s",
317                     __FUNCTION__, supportedPreviewFrameRates.string());
318         }
319         params.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES,
320                 supportedPreviewFrameRates);
321     }
322 
323     Vector<Size> availableJpegSizes = getAvailableJpegSizes();
324     if (!availableJpegSizes.size()) return NO_INIT;
325 
326     pictureWidth = availableJpegSizes[0].width;
327     pictureHeight = availableJpegSizes[0].height;
328     if (fastInfo.supportsPreferredConfigs) {
329         Size suggestedJpegSize = getMaxSize(getPreferredJpegSizes());
330         pictureWidth = suggestedJpegSize.width;
331         pictureHeight = suggestedJpegSize.height;
332     }
333     pictureWidthLastSet = pictureWidth;
334     pictureHeightLastSet = pictureHeight;
335     pictureSizeOverriden = false;
336 
337     params.setPictureSize(pictureWidth,
338             pictureHeight);
339 
340     {
341         String8 supportedPictureSizes;
342         for (size_t i=0; i < availableJpegSizes.size(); i++) {
343             if (i != 0) supportedPictureSizes += ",";
344             supportedPictureSizes += String8::format("%dx%d",
345                     availableJpegSizes[i].width,
346                     availableJpegSizes[i].height);
347         }
348         params.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES,
349                 supportedPictureSizes);
350     }
351 
352     params.setPictureFormat(CameraParameters::PIXEL_FORMAT_JPEG);
353     params.set(CameraParameters::KEY_SUPPORTED_PICTURE_FORMATS,
354             CameraParameters::PIXEL_FORMAT_JPEG);
355 
356     camera_metadata_ro_entry_t availableJpegThumbnailSizes =
357         staticInfo(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES, 4);
358     if (!availableJpegThumbnailSizes.count) return NO_INIT;
359 
360     // Pick the largest thumbnail size that matches still image aspect ratio.
361     ALOG_ASSERT(pictureWidth > 0 && pictureHeight > 0,
362             "Invalid picture size, %d x %d", pictureWidth, pictureHeight);
363     float picAspectRatio = static_cast<float>(pictureWidth) / pictureHeight;
364     Size thumbnailSize =
365             getMaxSizeForRatio(
366                     picAspectRatio,
367                     &availableJpegThumbnailSizes.data.i32[0],
368                     availableJpegThumbnailSizes.count);
369     jpegThumbSize[0] = thumbnailSize.width;
370     jpegThumbSize[1] = thumbnailSize.height;
371 
372     params.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH,
373             jpegThumbSize[0]);
374     params.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT,
375             jpegThumbSize[1]);
376 
377     {
378         String8 supportedJpegThumbSizes;
379         for (size_t i=0; i < availableJpegThumbnailSizes.count; i += 2) {
380             if (i != 0) supportedJpegThumbSizes += ",";
381             supportedJpegThumbSizes += String8::format("%dx%d",
382                     availableJpegThumbnailSizes.data.i32[i],
383                     availableJpegThumbnailSizes.data.i32[i+1]);
384         }
385         params.set(CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES,
386                 supportedJpegThumbSizes);
387     }
388 
389     jpegThumbQuality = 90;
390     params.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY,
391             jpegThumbQuality);
392     jpegQuality = 90;
393     params.set(CameraParameters::KEY_JPEG_QUALITY,
394             jpegQuality);
395     jpegRotation = 0;
396     params.set(CameraParameters::KEY_ROTATION,
397             jpegRotation);
398 
399     gpsEnabled = false;
400     gpsCoordinates[0] = 0.0;
401     gpsCoordinates[1] = 0.0;
402     gpsCoordinates[2] = 0.0;
403     gpsTimestamp = 0;
404     gpsProcessingMethod = "unknown";
405     // GPS fields in CameraParameters are not set by implementation
406 
407     wbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
408     params.set(CameraParameters::KEY_WHITE_BALANCE,
409             CameraParameters::WHITE_BALANCE_AUTO);
410 
411     camera_metadata_ro_entry_t availableWhiteBalanceModes =
412         staticInfo(ANDROID_CONTROL_AWB_AVAILABLE_MODES, 0, 0, false);
413     if (!availableWhiteBalanceModes.count) {
414         params.set(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE,
415                 CameraParameters::WHITE_BALANCE_AUTO);
416     } else {
417         String8 supportedWhiteBalance;
418         bool addComma = false;
419         for (size_t i=0; i < availableWhiteBalanceModes.count; i++) {
420             if (addComma) supportedWhiteBalance += ",";
421             addComma = true;
422             switch (availableWhiteBalanceModes.data.u8[i]) {
423             case ANDROID_CONTROL_AWB_MODE_AUTO:
424                 supportedWhiteBalance +=
425                     CameraParameters::WHITE_BALANCE_AUTO;
426                 break;
427             case ANDROID_CONTROL_AWB_MODE_INCANDESCENT:
428                 supportedWhiteBalance +=
429                     CameraParameters::WHITE_BALANCE_INCANDESCENT;
430                 break;
431             case ANDROID_CONTROL_AWB_MODE_FLUORESCENT:
432                 supportedWhiteBalance +=
433                     CameraParameters::WHITE_BALANCE_FLUORESCENT;
434                 break;
435             case ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT:
436                 supportedWhiteBalance +=
437                     CameraParameters::WHITE_BALANCE_WARM_FLUORESCENT;
438                 break;
439             case ANDROID_CONTROL_AWB_MODE_DAYLIGHT:
440                 supportedWhiteBalance +=
441                     CameraParameters::WHITE_BALANCE_DAYLIGHT;
442                 break;
443             case ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT:
444                 supportedWhiteBalance +=
445                     CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT;
446                 break;
447             case ANDROID_CONTROL_AWB_MODE_TWILIGHT:
448                 supportedWhiteBalance +=
449                     CameraParameters::WHITE_BALANCE_TWILIGHT;
450                 break;
451             case ANDROID_CONTROL_AWB_MODE_SHADE:
452                 supportedWhiteBalance +=
453                     CameraParameters::WHITE_BALANCE_SHADE;
454                 break;
455             // Skipping values not mappable to v1 API
456             case ANDROID_CONTROL_AWB_MODE_OFF:
457                 addComma = false;
458                 break;
459             default:
460                 ALOGW("%s: Camera %d: Unknown white balance value: %d",
461                         __FUNCTION__, cameraId,
462                         availableWhiteBalanceModes.data.u8[i]);
463                 addComma = false;
464                 break;
465             }
466         }
467         params.set(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE,
468                 supportedWhiteBalance);
469     }
470 
471     effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
472     params.set(CameraParameters::KEY_EFFECT,
473             CameraParameters::EFFECT_NONE);
474 
475     camera_metadata_ro_entry_t availableEffects =
476         staticInfo(ANDROID_CONTROL_AVAILABLE_EFFECTS, 0, 0, false);
477     if (!availableEffects.count) {
478         params.set(CameraParameters::KEY_SUPPORTED_EFFECTS,
479                 CameraParameters::EFFECT_NONE);
480     } else {
481         String8 supportedEffects;
482         bool addComma = false;
483         for (size_t i=0; i < availableEffects.count; i++) {
484             if (addComma) supportedEffects += ",";
485             addComma = true;
486             switch (availableEffects.data.u8[i]) {
487                 case ANDROID_CONTROL_EFFECT_MODE_OFF:
488                     supportedEffects +=
489                         CameraParameters::EFFECT_NONE;
490                     break;
491                 case ANDROID_CONTROL_EFFECT_MODE_MONO:
492                     supportedEffects +=
493                         CameraParameters::EFFECT_MONO;
494                     break;
495                 case ANDROID_CONTROL_EFFECT_MODE_NEGATIVE:
496                     supportedEffects +=
497                         CameraParameters::EFFECT_NEGATIVE;
498                     break;
499                 case ANDROID_CONTROL_EFFECT_MODE_SOLARIZE:
500                     supportedEffects +=
501                         CameraParameters::EFFECT_SOLARIZE;
502                     break;
503                 case ANDROID_CONTROL_EFFECT_MODE_SEPIA:
504                     supportedEffects +=
505                         CameraParameters::EFFECT_SEPIA;
506                     break;
507                 case ANDROID_CONTROL_EFFECT_MODE_POSTERIZE:
508                     supportedEffects +=
509                         CameraParameters::EFFECT_POSTERIZE;
510                     break;
511                 case ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD:
512                     supportedEffects +=
513                         CameraParameters::EFFECT_WHITEBOARD;
514                     break;
515                 case ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD:
516                     supportedEffects +=
517                         CameraParameters::EFFECT_BLACKBOARD;
518                     break;
519                 case ANDROID_CONTROL_EFFECT_MODE_AQUA:
520                     supportedEffects +=
521                         CameraParameters::EFFECT_AQUA;
522                     break;
523                 default:
524                     ALOGW("%s: Camera %d: Unknown effect value: %d",
525                         __FUNCTION__, cameraId, availableEffects.data.u8[i]);
526                     addComma = false;
527                     break;
528             }
529         }
530         params.set(CameraParameters::KEY_SUPPORTED_EFFECTS, supportedEffects);
531     }
532 
533     antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
534     params.set(CameraParameters::KEY_ANTIBANDING,
535             CameraParameters::ANTIBANDING_AUTO);
536 
537     camera_metadata_ro_entry_t availableAntibandingModes =
538         staticInfo(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES, 0, 0, false);
539     if (!availableAntibandingModes.count) {
540         params.set(CameraParameters::KEY_SUPPORTED_ANTIBANDING,
541                 CameraParameters::ANTIBANDING_OFF);
542     } else {
543         String8 supportedAntibanding;
544         bool addComma = false;
545         for (size_t i=0; i < availableAntibandingModes.count; i++) {
546             if (addComma) supportedAntibanding += ",";
547             addComma = true;
548             switch (availableAntibandingModes.data.u8[i]) {
549                 case ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF:
550                     supportedAntibanding +=
551                         CameraParameters::ANTIBANDING_OFF;
552                     break;
553                 case ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ:
554                     supportedAntibanding +=
555                         CameraParameters::ANTIBANDING_50HZ;
556                     break;
557                 case ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ:
558                     supportedAntibanding +=
559                         CameraParameters::ANTIBANDING_60HZ;
560                     break;
561                 case ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO:
562                     supportedAntibanding +=
563                         CameraParameters::ANTIBANDING_AUTO;
564                     break;
565                 default:
566                     ALOGW("%s: Camera %d: Unknown antibanding value: %d",
567                         __FUNCTION__, cameraId,
568                             availableAntibandingModes.data.u8[i]);
569                     addComma = false;
570                     break;
571             }
572         }
573         params.set(CameraParameters::KEY_SUPPORTED_ANTIBANDING,
574                 supportedAntibanding);
575     }
576 
577     sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
578     params.set(CameraParameters::KEY_SCENE_MODE,
579             CameraParameters::SCENE_MODE_AUTO);
580 
581     camera_metadata_ro_entry_t availableSceneModes =
582         staticInfo(ANDROID_CONTROL_AVAILABLE_SCENE_MODES, 0, 0, false);
583     if (!availableSceneModes.count) {
584         params.remove(CameraParameters::KEY_SCENE_MODE);
585     } else {
586         String8 supportedSceneModes(CameraParameters::SCENE_MODE_AUTO);
587         bool addComma = true;
588         bool noSceneModes = false;
589         for (size_t i=0; i < availableSceneModes.count; i++) {
590             if (addComma) supportedSceneModes += ",";
591             addComma = true;
592             switch (availableSceneModes.data.u8[i]) {
593                 case ANDROID_CONTROL_SCENE_MODE_DISABLED:
594                     noSceneModes = true;
595                     break;
596                 case ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY:
597                     // Face priority can be used as alternate default if supported.
598                     // Per API contract it shouldn't override the user set flash,
599                     // white balance and focus modes.
600                     mDefaultSceneMode = availableSceneModes.data.u8[i];
601                     // Not in old API
602                     addComma = false;
603                     break;
604                 case ANDROID_CONTROL_SCENE_MODE_ACTION:
605                     supportedSceneModes +=
606                         CameraParameters::SCENE_MODE_ACTION;
607                     break;
608                 case ANDROID_CONTROL_SCENE_MODE_PORTRAIT:
609                     supportedSceneModes +=
610                         CameraParameters::SCENE_MODE_PORTRAIT;
611                     break;
612                 case ANDROID_CONTROL_SCENE_MODE_LANDSCAPE:
613                     supportedSceneModes +=
614                         CameraParameters::SCENE_MODE_LANDSCAPE;
615                     break;
616                 case ANDROID_CONTROL_SCENE_MODE_NIGHT:
617                     supportedSceneModes +=
618                         CameraParameters::SCENE_MODE_NIGHT;
619                     break;
620                 case ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT:
621                     supportedSceneModes +=
622                         CameraParameters::SCENE_MODE_NIGHT_PORTRAIT;
623                     break;
624                 case ANDROID_CONTROL_SCENE_MODE_THEATRE:
625                     supportedSceneModes +=
626                         CameraParameters::SCENE_MODE_THEATRE;
627                     break;
628                 case ANDROID_CONTROL_SCENE_MODE_BEACH:
629                     supportedSceneModes +=
630                         CameraParameters::SCENE_MODE_BEACH;
631                     break;
632                 case ANDROID_CONTROL_SCENE_MODE_SNOW:
633                     supportedSceneModes +=
634                         CameraParameters::SCENE_MODE_SNOW;
635                     break;
636                 case ANDROID_CONTROL_SCENE_MODE_SUNSET:
637                     supportedSceneModes +=
638                         CameraParameters::SCENE_MODE_SUNSET;
639                     break;
640                 case ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO:
641                     supportedSceneModes +=
642                         CameraParameters::SCENE_MODE_STEADYPHOTO;
643                     break;
644                 case ANDROID_CONTROL_SCENE_MODE_FIREWORKS:
645                     supportedSceneModes +=
646                         CameraParameters::SCENE_MODE_FIREWORKS;
647                     break;
648                 case ANDROID_CONTROL_SCENE_MODE_SPORTS:
649                     supportedSceneModes +=
650                         CameraParameters::SCENE_MODE_SPORTS;
651                     break;
652                 case ANDROID_CONTROL_SCENE_MODE_PARTY:
653                     supportedSceneModes +=
654                         CameraParameters::SCENE_MODE_PARTY;
655                     break;
656                 case ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT:
657                     supportedSceneModes +=
658                         CameraParameters::SCENE_MODE_CANDLELIGHT;
659                     break;
660                 case ANDROID_CONTROL_SCENE_MODE_BARCODE:
661                     supportedSceneModes +=
662                         CameraParameters::SCENE_MODE_BARCODE;
663                     break;
664                 case ANDROID_CONTROL_SCENE_MODE_HDR:
665                     supportedSceneModes +=
666                         CameraParameters::SCENE_MODE_HDR;
667                     break;
668                 default:
669                     ALOGW("%s: Camera %d: Unknown scene mode value: %d",
670                         __FUNCTION__, cameraId,
671                             availableSceneModes.data.u8[i]);
672                     addComma = false;
673                     break;
674             }
675         }
676         if (!noSceneModes) {
677             params.set(CameraParameters::KEY_SUPPORTED_SCENE_MODES,
678                     supportedSceneModes);
679         } else {
680             params.remove(CameraParameters::KEY_SCENE_MODE);
681         }
682     }
683 
684     bool isFlashAvailable = false;
685     camera_metadata_ro_entry_t flashAvailable =
686         staticInfo(ANDROID_FLASH_INFO_AVAILABLE, 0, 1, false);
687     if (flashAvailable.count) {
688         isFlashAvailable = flashAvailable.data.u8[0];
689     }
690 
691     camera_metadata_ro_entry_t availableAeModes =
692         staticInfo(ANDROID_CONTROL_AE_AVAILABLE_MODES, 0, 0, false);
693 
694     flashMode = Parameters::FLASH_MODE_OFF;
695     if (isFlashAvailable) {
696         params.set(CameraParameters::KEY_FLASH_MODE,
697                 CameraParameters::FLASH_MODE_OFF);
698 
699         String8 supportedFlashModes(CameraParameters::FLASH_MODE_OFF);
700         supportedFlashModes = supportedFlashModes +
701             "," + CameraParameters::FLASH_MODE_AUTO +
702             "," + CameraParameters::FLASH_MODE_ON +
703             "," + CameraParameters::FLASH_MODE_TORCH;
704         for (size_t i=0; i < availableAeModes.count; i++) {
705             if (availableAeModes.data.u8[i] ==
706                     ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE) {
707                 supportedFlashModes = supportedFlashModes + "," +
708                     CameraParameters::FLASH_MODE_RED_EYE;
709                 break;
710             }
711         }
712         params.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES,
713                 supportedFlashModes);
714     } else {
715         // No flash means null flash mode and supported flash modes keys, so
716         // remove them just to be safe
717         params.remove(CameraParameters::KEY_FLASH_MODE);
718         params.remove(CameraParameters::KEY_SUPPORTED_FLASH_MODES);
719     }
720 
721     camera_metadata_ro_entry_t minFocusDistance =
722         staticInfo(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE, 0, 1, false);
723 
724     camera_metadata_ro_entry_t availableAfModes =
725         staticInfo(ANDROID_CONTROL_AF_AVAILABLE_MODES, 0, 0, false);
726 
727     if (!minFocusDistance.count || minFocusDistance.data.f[0] == 0) {
728         // Fixed-focus lens
729         focusMode = Parameters::FOCUS_MODE_FIXED;
730         params.set(CameraParameters::KEY_FOCUS_MODE,
731                 CameraParameters::FOCUS_MODE_FIXED);
732         params.set(CameraParameters::KEY_SUPPORTED_FOCUS_MODES,
733                 CameraParameters::FOCUS_MODE_FIXED);
734     } else {
735         focusMode = Parameters::FOCUS_MODE_AUTO;
736         params.set(CameraParameters::KEY_FOCUS_MODE,
737                 CameraParameters::FOCUS_MODE_AUTO);
738         String8 supportedFocusModes;
739         bool addComma = false;
740         camera_metadata_ro_entry_t focusDistanceCalibration =
741             staticInfo(ANDROID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION, 0, 0, false);
742 
743         if (focusDistanceCalibration.count &&
744                 focusDistanceCalibration.data.u8[0] !=
745                 ANDROID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_UNCALIBRATED) {
746             supportedFocusModes += CameraParameters::FOCUS_MODE_INFINITY;
747             addComma = true;
748         }
749 
750         for (size_t i=0; i < availableAfModes.count; i++) {
751             if (addComma) supportedFocusModes += ",";
752             addComma = true;
753             switch (availableAfModes.data.u8[i]) {
754                 case ANDROID_CONTROL_AF_MODE_AUTO:
755                     supportedFocusModes +=
756                         CameraParameters::FOCUS_MODE_AUTO;
757                     break;
758                 case ANDROID_CONTROL_AF_MODE_MACRO:
759                     supportedFocusModes +=
760                         CameraParameters::FOCUS_MODE_MACRO;
761                     break;
762                 case ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO:
763                     supportedFocusModes +=
764                         CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO;
765                     break;
766                 case ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE:
767                     supportedFocusModes +=
768                         CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE;
769                     break;
770                 case ANDROID_CONTROL_AF_MODE_EDOF:
771                     supportedFocusModes +=
772                         CameraParameters::FOCUS_MODE_EDOF;
773                     break;
774                 // Not supported in old API
775                 case ANDROID_CONTROL_AF_MODE_OFF:
776                     addComma = false;
777                     break;
778                 default:
779                     ALOGW("%s: Camera %d: Unknown AF mode value: %d",
780                         __FUNCTION__, cameraId, availableAfModes.data.u8[i]);
781                     addComma = false;
782                     break;
783             }
784         }
785         params.set(CameraParameters::KEY_SUPPORTED_FOCUS_MODES,
786                 supportedFocusModes);
787     }
788     focusState = ANDROID_CONTROL_AF_STATE_INACTIVE;
789     shadowFocusMode = FOCUS_MODE_INVALID;
790 
791     aeState = ANDROID_CONTROL_AE_STATE_INACTIVE;
792     camera_metadata_ro_entry_t max3aRegions = staticInfo(ANDROID_CONTROL_MAX_REGIONS,
793             Parameters::NUM_REGION, Parameters::NUM_REGION);
794     if (max3aRegions.count != Parameters::NUM_REGION) return NO_INIT;
795 
796     int32_t maxNumFocusAreas = 0;
797     if (focusMode != Parameters::FOCUS_MODE_FIXED) {
798         maxNumFocusAreas = max3aRegions.data.i32[Parameters::REGION_AF];
799     }
800     params.set(CameraParameters::KEY_MAX_NUM_FOCUS_AREAS, maxNumFocusAreas);
801     params.set(CameraParameters::KEY_FOCUS_AREAS,
802             "(0,0,0,0,0)");
803     focusingAreas.clear();
804     focusingAreas.add(Parameters::Area(0,0,0,0,0));
805 
806     params.setFloat(CameraParameters::KEY_FOCAL_LENGTH, fastInfo.defaultFocalLength);
807 
808     float horizFov, vertFov;
809     res = calculatePictureFovs(&horizFov, &vertFov);
810     if (res != OK) {
811         ALOGE("%s: Can't calculate field of views!", __FUNCTION__);
812         return res;
813     }
814 
815     params.setFloat(CameraParameters::KEY_HORIZONTAL_VIEW_ANGLE, horizFov);
816     params.setFloat(CameraParameters::KEY_VERTICAL_VIEW_ANGLE, vertFov);
817 
818     exposureCompensation = 0;
819     params.set(CameraParameters::KEY_EXPOSURE_COMPENSATION,
820                 exposureCompensation);
821 
822     camera_metadata_ro_entry_t exposureCompensationRange =
823         staticInfo(ANDROID_CONTROL_AE_COMPENSATION_RANGE, 2, 2);
824     if (!exposureCompensationRange.count) return NO_INIT;
825 
826     params.set(CameraParameters::KEY_MAX_EXPOSURE_COMPENSATION,
827             exposureCompensationRange.data.i32[1]);
828     params.set(CameraParameters::KEY_MIN_EXPOSURE_COMPENSATION,
829             exposureCompensationRange.data.i32[0]);
830 
831     camera_metadata_ro_entry_t exposureCompensationStep =
832         staticInfo(ANDROID_CONTROL_AE_COMPENSATION_STEP, 1, 1);
833     if (!exposureCompensationStep.count) return NO_INIT;
834 
835     params.setFloat(CameraParameters::KEY_EXPOSURE_COMPENSATION_STEP,
836             (float)exposureCompensationStep.data.r[0].numerator /
837             exposureCompensationStep.data.r[0].denominator);
838 
839     autoExposureLock = false;
840     autoExposureLockAvailable = false;
841     camera_metadata_ro_entry_t exposureLockAvailable =
842         staticInfo(ANDROID_CONTROL_AE_LOCK_AVAILABLE, 1, 1);
843     if ((0 < exposureLockAvailable.count) &&
844             (ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE ==
845                     exposureLockAvailable.data.u8[0])) {
846         params.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK,
847                 CameraParameters::FALSE);
848         params.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK_SUPPORTED,
849                    CameraParameters::TRUE);
850         autoExposureLockAvailable = true;
851     } else {
852         params.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK_SUPPORTED,
853                    CameraParameters::FALSE);
854     }
855 
856     autoWhiteBalanceLock = false;
857     autoWhiteBalanceLockAvailable = false;
858     camera_metadata_ro_entry_t whitebalanceLockAvailable =
859         staticInfo(ANDROID_CONTROL_AWB_LOCK_AVAILABLE, 1, 1);
860     if ((0 < whitebalanceLockAvailable.count) &&
861             (ANDROID_CONTROL_AWB_LOCK_AVAILABLE_TRUE ==
862                     whitebalanceLockAvailable.data.u8[0])) {
863         params.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK,
864                 CameraParameters::FALSE);
865         params.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED,
866                 CameraParameters::TRUE);
867         autoWhiteBalanceLockAvailable = true;
868     } else {
869         params.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED,
870                 CameraParameters::FALSE);
871     }
872 
873     meteringAreas.add(Parameters::Area(0, 0, 0, 0, 0));
874     params.set(CameraParameters::KEY_MAX_NUM_METERING_AREAS,
875             max3aRegions.data.i32[Parameters::REGION_AE]);
876     params.set(CameraParameters::KEY_METERING_AREAS,
877             "(0,0,0,0,0)");
878 
879     zoom = 0;
880     zoomAvailable = false;
881     camera_metadata_ro_entry_t maxDigitalZoom =
882         staticInfo(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM, /*minCount*/1, /*maxCount*/1);
883     if (!maxDigitalZoom.count) return NO_INIT;
884 
885     if (fabs(maxDigitalZoom.data.f[0] - 1.f) > 0.00001f) {
886         params.set(CameraParameters::KEY_ZOOM, zoom);
887 
888         {
889             String8 zoomRatios;
890             float zoom = 1.f;
891             float zoomIncrement = (maxDigitalZoom.data.f[0] - zoom) /
892                     (NUM_ZOOM_STEPS-1);
893             bool addComma = false;
894             int previousZoom = -1;
895             size_t zoomSteps = 0;
896             for (size_t i = 0; i < NUM_ZOOM_STEPS; i++) {
897                 int currentZoom = static_cast<int>(zoom * 100);
898                 if (previousZoom == currentZoom) {
899                     zoom += zoomIncrement;
900                     continue;
901                 }
902                 if (addComma) zoomRatios += ",";
903                 addComma = true;
904                 zoomRatios += String8::format("%d", currentZoom);
905                 zoom += zoomIncrement;
906                 previousZoom = currentZoom;
907                 zoomSteps++;
908             }
909 
910             if (zoomSteps > 0) {
911                 params.set(CameraParameters::KEY_ZOOM_RATIOS, zoomRatios);
912                 params.set(CameraParameters::KEY_ZOOM_SUPPORTED,
913                         CameraParameters::TRUE);
914                 params.set(CameraParameters::KEY_MAX_ZOOM, zoomSteps - 1);
915                 zoomAvailable = true;
916             } else {
917                 params.set(CameraParameters::KEY_ZOOM_SUPPORTED,
918                         CameraParameters::FALSE);
919             }
920         }
921 
922     } else {
923         params.set(CameraParameters::KEY_ZOOM_SUPPORTED,
924                 CameraParameters::FALSE);
925     }
926     params.set(CameraParameters::KEY_SMOOTH_ZOOM_SUPPORTED,
927             CameraParameters::FALSE);
928 
929     params.set(CameraParameters::KEY_FOCUS_DISTANCES,
930             "Infinity,Infinity,Infinity");
931 
932     params.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_HW,
933             fastInfo.maxFaces);
934     params.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_SW,
935             0);
936 
937     params.set(CameraParameters::KEY_VIDEO_FRAME_FORMAT,
938             CameraParameters::PIXEL_FORMAT_ANDROID_OPAQUE);
939 
940     recordingHint = false;
941     params.set(CameraParameters::KEY_RECORDING_HINT,
942             CameraParameters::FALSE);
943 
944     params.set(CameraParameters::KEY_VIDEO_SNAPSHOT_SUPPORTED,
945             CameraParameters::TRUE);
946 
947     videoStabilization = false;
948     params.set(CameraParameters::KEY_VIDEO_STABILIZATION,
949             CameraParameters::FALSE);
950 
951     camera_metadata_ro_entry_t availableVideoStabilizationModes =
952         staticInfo(ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES, 0, 0,
953                 false);
954 
955     if (availableVideoStabilizationModes.count > 1) {
956         params.set(CameraParameters::KEY_VIDEO_STABILIZATION_SUPPORTED,
957                 CameraParameters::TRUE);
958     } else {
959         params.set(CameraParameters::KEY_VIDEO_STABILIZATION_SUPPORTED,
960                 CameraParameters::FALSE);
961     }
962 
963     // Set up initial state for non-Camera.Parameters state variables
964     videoFormat = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
965     videoDataSpace = HAL_DATASPACE_V0_BT709;
966     videoBufferMode = hardware::ICamera::VIDEO_BUFFER_MODE_DATA_CALLBACK_YUV;
967     playShutterSound = true;
968     enableFaceDetect = false;
969 
970     enableFocusMoveMessages = false;
971     afTriggerCounter = 1;
972     afStateCounter = 0;
973     currentAfTriggerId = -1;
974     afInMotion = false;
975 
976     precaptureTriggerCounter = 1;
977 
978     takePictureCounter = 0;
979 
980     previewCallbackFlags = 0;
981     previewCallbackOneShot = false;
982     previewCallbackSurface = false;
983 
984     Size maxJpegSize = getMaxSize(getAvailableJpegSizes());
985     int64_t minFrameDurationNs = getJpegStreamMinFrameDurationNs(maxJpegSize);
986 
987     slowJpegMode = isSlowJpegModeForced || minFrameDurationNs > kSlowJpegModeThreshold;
988     if (slowJpegMode) {
989         // Slow jpeg devices does not support video snapshot without
990         // slowing down preview.
991         // TODO: support video size video snapshot only?
992         params.set(CameraParameters::KEY_VIDEO_SNAPSHOT_SUPPORTED,
993             CameraParameters::FALSE);
994     }
995 
996     isZslReprocessPresent = false;
997     camera_metadata_ro_entry_t availableCapabilities =
998         staticInfo(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
999     if (0 < availableCapabilities.count) {
1000         const uint8_t *caps = availableCapabilities.data.u8;
1001         for (size_t i = 0; i < availableCapabilities.count; i++) {
1002             if (ANDROID_REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING ==
1003                     caps[i]) {
1004                 isZslReprocessPresent = true;
1005                 break;
1006             }
1007         }
1008     }
1009 
1010     isDistortionCorrectionSupported = false;
1011     camera_metadata_ro_entry_t distortionCorrectionModes =
1012             staticInfo(ANDROID_DISTORTION_CORRECTION_AVAILABLE_MODES);
1013     for (size_t i = 0; i < distortionCorrectionModes.count; i++) {
1014         if (distortionCorrectionModes.data.u8[i] !=
1015                 ANDROID_DISTORTION_CORRECTION_MODE_OFF) {
1016             isDistortionCorrectionSupported = true;
1017             break;
1018         }
1019     }
1020 
1021     if (isDeviceZslSupported || slowJpegMode ||
1022             property_get_bool("camera.disable_zsl_mode", false)) {
1023         ALOGI("Camera %d: Disabling ZSL mode", cameraId);
1024         allowZslMode = false;
1025     } else {
1026         allowZslMode = isZslReprocessPresent;
1027     }
1028 
1029     ALOGI("%s: allowZslMode: %d slowJpegMode %d", __FUNCTION__, allowZslMode, slowJpegMode);
1030 
1031     state = STOPPED;
1032 
1033     paramsFlattened = params.flatten();
1034 
1035     return OK;
1036 }
1037 
get() const1038 String8 Parameters::get() const {
1039     return paramsFlattened;
1040 }
1041 
buildFastInfo(CameraDeviceBase * device)1042 status_t Parameters::buildFastInfo(CameraDeviceBase *device) {
1043 
1044     camera_metadata_ro_entry_t activeArraySize =
1045         staticInfo(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE, 2, 4);
1046     if (!activeArraySize.count) return NO_INIT;
1047     int32_t arrayWidth;
1048     int32_t arrayHeight;
1049     if (activeArraySize.count == 2) {
1050         ALOGW("%s: Camera %d: activeArraySize is missing xmin/ymin!",
1051                 __FUNCTION__, cameraId);
1052         arrayWidth = activeArraySize.data.i32[0];
1053         arrayHeight = activeArraySize.data.i32[1];
1054     } else if (activeArraySize.count == 4) {
1055         arrayWidth = activeArraySize.data.i32[2];
1056         arrayHeight = activeArraySize.data.i32[3];
1057     } else return NO_INIT;
1058 
1059     fastInfo.supportsPreferredConfigs =
1060         info->exists(ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS);
1061 
1062     // We'll set the target FPS range for still captures to be as wide
1063     // as possible to give the HAL maximum latitude for exposure selection
1064     camera_metadata_ro_entry_t availableFpsRanges =
1065         staticInfo(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES, 2);
1066     if (availableFpsRanges.count < 2 || availableFpsRanges.count % 2 != 0) {
1067         return NO_INIT;
1068     }
1069 
1070     // Get supported preview fps ranges, up to default maximum.
1071     Vector<Size> supportedPreviewSizes;
1072     Vector<FpsRange> supportedPreviewFpsRanges;
1073     Size previewSizeBound = { MAX_PREVIEW_WIDTH, MAX_PREVIEW_HEIGHT };
1074     if (fastInfo.supportsPreferredConfigs) {
1075         previewSizeBound = getMaxSize(getPreferredPreviewSizes());
1076     }
1077     status_t res = getFilteredSizes(
1078         Size{0, 0}, previewSizeBound, &supportedPreviewSizes);
1079     if (res != OK) return res;
1080     for (size_t i=0; i < availableFpsRanges.count; i += 2) {
1081         if (!isFpsSupported(supportedPreviewSizes,
1082                 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, availableFpsRanges.data.i32[i+1]) ||
1083                 availableFpsRanges.data.i32[i+1] > MAX_DEFAULT_FPS) {
1084             continue;
1085         }
1086         FpsRange fpsRange = {availableFpsRanges.data.i32[i], availableFpsRanges.data.i32[i+1]};
1087         supportedPreviewFpsRanges.add(fpsRange);
1088     }
1089     if (supportedPreviewFpsRanges.size() == 0) {
1090         ALOGE("Supported preview fps range is empty");
1091         return NO_INIT;
1092     }
1093 
1094     int32_t bestStillCaptureFpsRange[2] = {
1095         supportedPreviewFpsRanges[0].low, supportedPreviewFpsRanges[0].high
1096     };
1097     int32_t curRange =
1098             bestStillCaptureFpsRange[1] - bestStillCaptureFpsRange[0];
1099     for (size_t i = 1; i < supportedPreviewFpsRanges.size(); i ++) {
1100         int32_t nextRange =
1101                 supportedPreviewFpsRanges[i].high -
1102                 supportedPreviewFpsRanges[i].low;
1103         if ( (nextRange > curRange) ||       // Maximize size of FPS range first
1104                 (nextRange == curRange &&    // Then minimize low-end FPS
1105                  bestStillCaptureFpsRange[0] > supportedPreviewFpsRanges[i].low)) {
1106 
1107             bestStillCaptureFpsRange[0] = supportedPreviewFpsRanges[i].low;
1108             bestStillCaptureFpsRange[1] = supportedPreviewFpsRanges[i].high;
1109             curRange = nextRange;
1110         }
1111     }
1112 
1113     camera_metadata_ro_entry_t availableFaceDetectModes =
1114         staticInfo(ANDROID_STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES, 0, 0,
1115                 false);
1116 
1117     uint8_t bestFaceDetectMode =
1118         ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
1119     for (size_t i = 0 ; i < availableFaceDetectModes.count; i++) {
1120         switch (availableFaceDetectModes.data.u8[i]) {
1121             case ANDROID_STATISTICS_FACE_DETECT_MODE_OFF:
1122                 break;
1123             case ANDROID_STATISTICS_FACE_DETECT_MODE_SIMPLE:
1124                 if (bestFaceDetectMode !=
1125                         ANDROID_STATISTICS_FACE_DETECT_MODE_FULL) {
1126                     bestFaceDetectMode =
1127                         ANDROID_STATISTICS_FACE_DETECT_MODE_SIMPLE;
1128                 }
1129                 break;
1130             case ANDROID_STATISTICS_FACE_DETECT_MODE_FULL:
1131                 bestFaceDetectMode =
1132                     ANDROID_STATISTICS_FACE_DETECT_MODE_FULL;
1133                 break;
1134             default:
1135                 ALOGE("%s: Camera %d: Unknown face detect mode %d:",
1136                         __FUNCTION__, cameraId,
1137                         availableFaceDetectModes.data.u8[i]);
1138                 return NO_INIT;
1139         }
1140     }
1141 
1142     int32_t maxFaces = 0;
1143     camera_metadata_ro_entry_t maxFacesDetected =
1144         staticInfo(ANDROID_STATISTICS_INFO_MAX_FACE_COUNT, 0, 1, false);
1145     if (maxFacesDetected.count) {
1146         maxFaces = maxFacesDetected.data.i32[0];
1147     }
1148 
1149     camera_metadata_ro_entry_t availableSceneModes =
1150         staticInfo(ANDROID_CONTROL_AVAILABLE_SCENE_MODES, 0, 0, false);
1151     camera_metadata_ro_entry_t sceneModeOverrides =
1152         staticInfo(ANDROID_CONTROL_SCENE_MODE_OVERRIDES, 0, 0, false);
1153     camera_metadata_ro_entry_t minFocusDistance =
1154         staticInfo(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE, 0, 0, false);
1155     bool fixedLens = minFocusDistance.count == 0 ||
1156         minFocusDistance.data.f[0] == 0;
1157 
1158     camera_metadata_ro_entry_t focusDistanceCalibration =
1159             staticInfo(ANDROID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION, 0, 0,
1160                     false);
1161     bool canFocusInfinity = (focusDistanceCalibration.count &&
1162             focusDistanceCalibration.data.u8[0] !=
1163             ANDROID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_UNCALIBRATED);
1164 
1165     res = getDefaultFocalLength(device);
1166     if (res != OK) return res;
1167 
1168     SortedVector<int32_t> availableFormats = getAvailableOutputFormats();
1169     if (!availableFormats.size()) return NO_INIT;
1170 
1171     if (sceneModeOverrides.count > 0) {
1172         // sceneModeOverrides is defined to have 3 entries for each scene mode,
1173         // which are AE, AWB, and AF override modes the HAL wants for that scene
1174         // mode.
1175         const size_t kModesPerSceneMode = 3;
1176         if (sceneModeOverrides.count !=
1177                 availableSceneModes.count * kModesPerSceneMode) {
1178             ALOGE("%s: Camera %d: Scene mode override list is an "
1179                     "unexpected size: %zu (expected %zu)", __FUNCTION__,
1180                     cameraId, sceneModeOverrides.count,
1181                     availableSceneModes.count * kModesPerSceneMode);
1182             return NO_INIT;
1183         }
1184         for (size_t i = 0; i < availableSceneModes.count; i++) {
1185             DeviceInfo::OverrideModes modes;
1186             uint8_t aeMode =
1187                     sceneModeOverrides.data.u8[i * kModesPerSceneMode + 0];
1188             switch(aeMode) {
1189                 case ANDROID_CONTROL_AE_MODE_ON:
1190                     modes.flashMode = FLASH_MODE_OFF;
1191                     break;
1192                 case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH:
1193                     modes.flashMode = FLASH_MODE_AUTO;
1194                     break;
1195                 case ANDROID_CONTROL_AE_MODE_ON_ALWAYS_FLASH:
1196                     modes.flashMode = FLASH_MODE_ON;
1197                     break;
1198                 case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE:
1199                     modes.flashMode = FLASH_MODE_RED_EYE;
1200                     break;
1201                 default:
1202                     ALOGE("%s: Unknown override AE mode: %d", __FUNCTION__,
1203                             aeMode);
1204                     modes.flashMode = FLASH_MODE_INVALID;
1205                     break;
1206             }
1207             modes.wbMode =
1208                     sceneModeOverrides.data.u8[i * kModesPerSceneMode + 1];
1209             uint8_t afMode =
1210                     sceneModeOverrides.data.u8[i * kModesPerSceneMode + 2];
1211             switch(afMode) {
1212                 case ANDROID_CONTROL_AF_MODE_OFF:
1213                     if (!fixedLens && !canFocusInfinity) {
1214                         ALOGE("%s: Camera %d: Scene mode override lists asks for"
1215                                 " fixed focus on a device with focuser but not"
1216                                 " calibrated for infinity focus", __FUNCTION__,
1217                                 cameraId);
1218                         return NO_INIT;
1219                     }
1220                     modes.focusMode = fixedLens ?
1221                             FOCUS_MODE_FIXED : FOCUS_MODE_INFINITY;
1222                     break;
1223                 case ANDROID_CONTROL_AF_MODE_AUTO:
1224                 case ANDROID_CONTROL_AF_MODE_MACRO:
1225                 case ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO:
1226                 case ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE:
1227                 case ANDROID_CONTROL_AF_MODE_EDOF:
1228                     modes.focusMode = static_cast<focusMode_t>(afMode);
1229                     break;
1230                 default:
1231                     ALOGE("%s: Unknown override AF mode: %d", __FUNCTION__,
1232                             afMode);
1233                     modes.focusMode = FOCUS_MODE_INVALID;
1234                     break;
1235             }
1236             fastInfo.sceneModeOverrides.add(availableSceneModes.data.u8[i],
1237                     modes);
1238         }
1239     }
1240 
1241     fastInfo.arrayWidth = arrayWidth;
1242     fastInfo.arrayHeight = arrayHeight;
1243     fastInfo.bestStillCaptureFpsRange[0] = bestStillCaptureFpsRange[0];
1244     fastInfo.bestStillCaptureFpsRange[1] = bestStillCaptureFpsRange[1];
1245     fastInfo.bestFaceDetectMode = bestFaceDetectMode;
1246     fastInfo.maxFaces = maxFaces;
1247 
1248     // Check if the HAL supports HAL_PIXEL_FORMAT_YCbCr_420_888
1249     fastInfo.useFlexibleYuv = false;
1250     for (size_t i = 0; i < availableFormats.size(); i++) {
1251         if (availableFormats[i] == HAL_PIXEL_FORMAT_YCbCr_420_888) {
1252             fastInfo.useFlexibleYuv = true;
1253             break;
1254         }
1255     }
1256     ALOGV("Camera %d: Flexible YUV %s supported",
1257             cameraId, fastInfo.useFlexibleYuv ? "is" : "is not");
1258 
1259     fastInfo.maxJpegSize = getMaxSize(getAvailableJpegSizes());
1260 
1261     isZslReprocessPresent = false;
1262     camera_metadata_ro_entry_t availableCapabilities =
1263         staticInfo(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
1264     if (0 < availableCapabilities.count) {
1265         const uint8_t *caps = availableCapabilities.data.u8;
1266         for (size_t i = 0; i < availableCapabilities.count; i++) {
1267             if (ANDROID_REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING ==
1268                     caps[i]) {
1269                 isZslReprocessPresent = true;
1270                 break;
1271             }
1272         }
1273     }
1274     if (isZslReprocessPresent) {
1275         Vector<StreamConfiguration> scs = getStreamConfigurations();
1276         Size maxPrivInputSize = {0, 0};
1277         for (const auto& sc : scs) {
1278             if (sc.isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT &&
1279                     sc.format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
1280                 if (sc.width * sc.height > maxPrivInputSize.width * maxPrivInputSize.height) {
1281                     maxPrivInputSize = {sc.width, sc.height};
1282                 }
1283             }
1284         }
1285         fastInfo.maxZslSize = maxPrivInputSize;
1286         fastInfo.usedZslSize = maxPrivInputSize;
1287     } else {
1288         fastInfo.maxZslSize = {0, 0};
1289     }
1290 
1291     return OK;
1292 }
1293 
buildQuirks()1294 status_t Parameters::buildQuirks() {
1295     camera_metadata_ro_entry_t entry;
1296     entry = info->find(ANDROID_QUIRKS_TRIGGER_AF_WITH_AUTO);
1297     quirks.triggerAfWithAuto = (entry.count != 0 && entry.data.u8[0] == 1);
1298     ALOGV_IF(quirks.triggerAfWithAuto, "Camera %d: Quirk triggerAfWithAuto enabled",
1299             cameraId);
1300 
1301     entry = info->find(ANDROID_QUIRKS_USE_ZSL_FORMAT);
1302     quirks.useZslFormat = (entry.count != 0 && entry.data.u8[0] == 1);
1303     ALOGV_IF(quirks.useZslFormat, "Camera %d: Quirk useZslFormat enabled",
1304             cameraId);
1305 
1306     entry = info->find(ANDROID_QUIRKS_METERING_CROP_REGION);
1307     quirks.meteringCropRegion = (entry.count != 0 && entry.data.u8[0] == 1);
1308     ALOGV_IF(quirks.meteringCropRegion, "Camera %d: Quirk meteringCropRegion"
1309                 " enabled", cameraId);
1310 
1311     entry = info->find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
1312     quirks.partialResults = (entry.count != 0 && entry.data.u8[0] == 1);
1313     ALOGV_IF(quirks.partialResults, "Camera %d: Quirk usePartialResult"
1314                 " enabled", cameraId);
1315 
1316     return OK;
1317 }
1318 
staticInfo(uint32_t tag,size_t minCount,size_t maxCount,bool required) const1319 camera_metadata_ro_entry_t Parameters::staticInfo(uint32_t tag,
1320         size_t minCount, size_t maxCount, bool required) const {
1321     camera_metadata_ro_entry_t entry = info->find(tag);
1322     const camera_metadata_t *metaBuffer = info->getAndLock();
1323 
1324     if (CC_UNLIKELY( entry.count == 0 ) && required) {
1325         const char* tagSection = get_local_camera_metadata_section_name(tag,
1326                 metaBuffer);
1327         if (tagSection == NULL) tagSection = "<unknown>";
1328         const char* tagName = get_local_camera_metadata_tag_name(tag,
1329                 metaBuffer);
1330         if (tagName == NULL) tagName = "<unknown>";
1331 
1332         ALOGE("Error finding static metadata entry '%s.%s' (%x)",
1333                 tagSection, tagName, tag);
1334     } else if (CC_UNLIKELY(
1335             (minCount != 0 && entry.count < minCount) ||
1336             (maxCount != 0 && entry.count > maxCount) ) ) {
1337         const char* tagSection = get_local_camera_metadata_section_name(tag,
1338                 metaBuffer);
1339         if (tagSection == NULL) tagSection = "<unknown>";
1340         const char* tagName = get_local_camera_metadata_tag_name(tag,
1341                 metaBuffer);
1342         if (tagName == NULL) tagName = "<unknown>";
1343         ALOGE("Malformed static metadata entry '%s.%s' (%x):"
1344                 "Expected between %zu and %zu values, but got %zu values",
1345                 tagSection, tagName, tag, minCount, maxCount, entry.count);
1346     }
1347     info->unlock(metaBuffer);
1348 
1349     return entry;
1350 }
1351 
set(const String8 & paramString)1352 status_t Parameters::set(const String8& paramString) {
1353     status_t res;
1354 
1355     CameraParameters2 newParams(paramString);
1356 
1357     // TODO: Currently ignoring any changes to supposedly read-only parameters
1358     // such as supported preview sizes, etc. Should probably produce an error if
1359     // they're changed.
1360 
1361     /** Extract and verify new parameters */
1362 
1363     size_t i;
1364 
1365     Parameters validatedParams(*this);
1366 
1367     // PREVIEW_SIZE
1368     newParams.getPreviewSize(&validatedParams.previewWidth,
1369             &validatedParams.previewHeight);
1370 
1371     if (validatedParams.previewWidth != previewWidth ||
1372             validatedParams.previewHeight != previewHeight) {
1373         if (state >= PREVIEW) {
1374             ALOGE("%s: Preview size cannot be updated when preview "
1375                     "is active! (Currently %d x %d, requested %d x %d",
1376                     __FUNCTION__,
1377                     previewWidth, previewHeight,
1378                     validatedParams.previewWidth, validatedParams.previewHeight);
1379             return BAD_VALUE;
1380         }
1381         for (i = 0; i < availablePreviewSizes.size(); i++) {
1382             if ((availablePreviewSizes[i].width ==
1383                     validatedParams.previewWidth) &&
1384                 (availablePreviewSizes[i].height ==
1385                     validatedParams.previewHeight)) break;
1386         }
1387         if (i == availablePreviewSizes.size()) {
1388             ALOGE("%s: Requested preview size %d x %d is not supported",
1389                     __FUNCTION__, validatedParams.previewWidth,
1390                     validatedParams.previewHeight);
1391             return BAD_VALUE;
1392         }
1393     }
1394 
1395     // RECORDING_HINT (always supported)
1396     validatedParams.recordingHint = boolFromString(
1397         newParams.get(CameraParameters::KEY_RECORDING_HINT) );
1398     IF_ALOGV() { // Avoid unused variable warning
1399         bool recordingHintChanged =
1400                 validatedParams.recordingHint != recordingHint;
1401         if (recordingHintChanged) {
1402             ALOGV("%s: Recording hint changed to %d",
1403                   __FUNCTION__, validatedParams.recordingHint);
1404         }
1405     }
1406 
1407     // PREVIEW_FPS_RANGE
1408 
1409     /**
1410      * Use the single FPS value if it was set later than the range.
1411      * Otherwise, use the range value.
1412      */
1413     bool fpsUseSingleValue;
1414     {
1415         const char *fpsRange, *fpsSingle;
1416 
1417         fpsSingle = newParams.get(CameraParameters::KEY_PREVIEW_FRAME_RATE);
1418         fpsRange = newParams.get(CameraParameters::KEY_PREVIEW_FPS_RANGE);
1419 
1420         /**
1421          * Pick either the range or the single key if only one was set.
1422          *
1423          * If both are set, pick the one that has greater set order.
1424          */
1425         if (fpsRange == NULL && fpsSingle == NULL) {
1426             ALOGE("%s: FPS was not set. One of %s or %s must be set.",
1427                   __FUNCTION__, CameraParameters::KEY_PREVIEW_FRAME_RATE,
1428                   CameraParameters::KEY_PREVIEW_FPS_RANGE);
1429             return BAD_VALUE;
1430         } else if (fpsRange == NULL) {
1431             fpsUseSingleValue = true;
1432             ALOGV("%s: FPS range not set, using FPS single value",
1433                   __FUNCTION__);
1434         } else if (fpsSingle == NULL) {
1435             fpsUseSingleValue = false;
1436             ALOGV("%s: FPS single not set, using FPS range value",
1437                   __FUNCTION__);
1438         } else {
1439             int fpsKeyOrder;
1440             res = newParams.compareSetOrder(
1441                     CameraParameters::KEY_PREVIEW_FRAME_RATE,
1442                     CameraParameters::KEY_PREVIEW_FPS_RANGE,
1443                     &fpsKeyOrder);
1444             LOG_ALWAYS_FATAL_IF(res != OK, "Impossibly bad FPS keys");
1445 
1446             fpsUseSingleValue = (fpsKeyOrder > 0);
1447 
1448         }
1449 
1450         ALOGV("%s: Preview FPS value is used from '%s'",
1451               __FUNCTION__, fpsUseSingleValue ? "single" : "range");
1452     }
1453     newParams.getPreviewFpsRange(&validatedParams.previewFpsRange[0],
1454             &validatedParams.previewFpsRange[1]);
1455 
1456     validatedParams.previewFpsRange[0] /= kFpsToApiScale;
1457     validatedParams.previewFpsRange[1] /= kFpsToApiScale;
1458 
1459     // Ignore the FPS range if the FPS single has higher precedence
1460     if (!fpsUseSingleValue) {
1461         ALOGV("%s: Preview FPS range (%d, %d)", __FUNCTION__,
1462                 validatedParams.previewFpsRange[0],
1463                 validatedParams.previewFpsRange[1]);
1464 
1465         camera_metadata_ro_entry_t availablePreviewFpsRanges =
1466             staticInfo(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES, 2);
1467         for (i = 0; i < availablePreviewFpsRanges.count; i += 2) {
1468             if ((availablePreviewFpsRanges.data.i32[i] ==
1469                     validatedParams.previewFpsRange[0]) &&
1470                 (availablePreviewFpsRanges.data.i32[i+1] ==
1471                     validatedParams.previewFpsRange[1]) ) {
1472                 break;
1473             }
1474         }
1475         if (i == availablePreviewFpsRanges.count) {
1476             ALOGE("%s: Requested preview FPS range %d - %d is not supported",
1477                 __FUNCTION__, validatedParams.previewFpsRange[0],
1478                     validatedParams.previewFpsRange[1]);
1479             return BAD_VALUE;
1480         }
1481     }
1482 
1483     // PREVIEW_FORMAT
1484     validatedParams.previewFormat =
1485             formatStringToEnum(newParams.getPreviewFormat());
1486     if (validatedParams.previewFormat != previewFormat) {
1487         if (state >= PREVIEW) {
1488             ALOGE("%s: Preview format cannot be updated when preview "
1489                     "is active!", __FUNCTION__);
1490             return BAD_VALUE;
1491         }
1492         SortedVector<int32_t> availableFormats = getAvailableOutputFormats();
1493         // If using flexible YUV, always support NV21/YV12. Otherwise, check
1494         // HAL's list.
1495         if (! (fastInfo.useFlexibleYuv &&
1496                 (validatedParams.previewFormat ==
1497                         HAL_PIXEL_FORMAT_YCrCb_420_SP ||
1498                  validatedParams.previewFormat ==
1499                         HAL_PIXEL_FORMAT_YV12) ) ) {
1500             // Not using flexible YUV format, so check explicitly
1501             for (i = 0; i < availableFormats.size(); i++) {
1502                 if (availableFormats[i] == validatedParams.previewFormat) break;
1503             }
1504             if (i == availableFormats.size()) {
1505                 ALOGE("%s: Requested preview format %s (0x%x) is not supported",
1506                         __FUNCTION__, newParams.getPreviewFormat(),
1507                         validatedParams.previewFormat);
1508                 return BAD_VALUE;
1509             }
1510         }
1511     }
1512 
1513     // PREVIEW_FRAME_RATE Deprecated
1514     // - Use only if the single FPS value was set later than the FPS range
1515     if (fpsUseSingleValue) {
1516         int previewFps = newParams.getPreviewFrameRate();
1517         ALOGV("%s: Preview FPS single value requested: %d",
1518               __FUNCTION__, previewFps);
1519         {
1520             camera_metadata_ro_entry_t availableFrameRates =
1521                 staticInfo(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES);
1522             /**
1523               * If recording hint is set, find the range that encompasses
1524               * previewFps with the largest min index.
1525               *
1526               * If recording hint is not set, find the range with previewFps
1527               * with the smallest min index.
1528               *
1529               * Either way, in case of multiple ranges, break the tie by
1530               * selecting the smaller range.
1531               *
1532               * Always select range within 30fps if one exists.
1533               */
1534 
1535             // all ranges which have previewFps
1536             Vector<Range> candidateRanges;
1537             Vector<Range> candidateFastRanges;
1538             for (i = 0; i < availableFrameRates.count; i+=2) {
1539                 Range r = {
1540                             availableFrameRates.data.i32[i],
1541                             availableFrameRates.data.i32[i+1]
1542                 };
1543                 if (!isFpsSupported(availablePreviewSizes,
1544                         HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, r.max)) {
1545                     continue;
1546                 }
1547 
1548                 if (r.min <= previewFps && previewFps <= r.max) {
1549                     if (r.max <= MAX_DEFAULT_FPS) {
1550                         candidateRanges.push(r);
1551                     } else {
1552                         candidateFastRanges.push(r);
1553                     }
1554                 }
1555             }
1556             if (candidateRanges.isEmpty() && candidateFastRanges.isEmpty()) {
1557                 ALOGE("%s: Requested preview frame rate %d is not supported",
1558                         __FUNCTION__, previewFps);
1559                 return BAD_VALUE;
1560             }
1561 
1562             // most applicable range with targetFps
1563             Vector<Range>& ranges =
1564                     candidateRanges.size() > 0 ? candidateRanges : candidateFastRanges;
1565             Range bestRange = ranges[0];
1566             for (i = 1; i < ranges.size(); ++i) {
1567                 Range r = ranges[i];
1568                 // Find by largest minIndex in recording mode
1569                 if (validatedParams.recordingHint) {
1570                     if (r.min > bestRange.min) {
1571                         bestRange = r;
1572                     }
1573                     else if (r.min == bestRange.min && r.max < bestRange.max) {
1574                         bestRange = r;
1575                     }
1576                 }
1577                 // Find by smallest minIndex in preview mode
1578                 else {
1579                     if (r.min < bestRange.min) {
1580                         bestRange = r;
1581                     }
1582                     else if (r.min == bestRange.min && r.max < bestRange.max) {
1583                         bestRange = r;
1584                     }
1585                 }
1586             }
1587 
1588             validatedParams.previewFpsRange[0] =
1589                     bestRange.min;
1590             validatedParams.previewFpsRange[1] =
1591                     bestRange.max;
1592 
1593             ALOGV("%s: New preview FPS range: %d, %d, recordingHint = %d",
1594                 __FUNCTION__,
1595                 validatedParams.previewFpsRange[0],
1596                 validatedParams.previewFpsRange[1],
1597                 validatedParams.recordingHint);
1598         }
1599     }
1600 
1601     /**
1602      * Update Preview FPS and Preview FPS ranges based on
1603      * what we actually set.
1604      *
1605      * This updates the API-visible (Camera.Parameters#getParameters) values of
1606      * the FPS fields, not only the internal versions.
1607      *
1608      * Order matters: The value that was set last takes precedence.
1609      * - If the client does a setParameters(getParameters()) we retain
1610      *   the same order for preview FPS.
1611      */
1612     if (!fpsUseSingleValue) {
1613         // Set fps single, then fps range (range wins)
1614         newParams.setPreviewFrameRate(
1615                 fpsFromRange(/*min*/validatedParams.previewFpsRange[0],
1616                              /*max*/validatedParams.previewFpsRange[1]));
1617         newParams.setPreviewFpsRange(
1618                 validatedParams.previewFpsRange[0] * kFpsToApiScale,
1619                 validatedParams.previewFpsRange[1] * kFpsToApiScale);
1620     } else {
1621         // Set fps range, then fps single (single wins)
1622         newParams.setPreviewFpsRange(
1623                 validatedParams.previewFpsRange[0] * kFpsToApiScale,
1624                 validatedParams.previewFpsRange[1] * kFpsToApiScale);
1625         // Set this to the same value, but with higher priority
1626         newParams.setPreviewFrameRate(
1627                 newParams.getPreviewFrameRate());
1628     }
1629 
1630     // PICTURE_SIZE
1631     newParams.getPictureSize(&validatedParams.pictureWidth,
1632             &validatedParams.pictureHeight);
1633     if (validatedParams.pictureWidth != pictureWidth ||
1634             validatedParams.pictureHeight != pictureHeight) {
1635         Vector<Size> availablePictureSizes = getAvailableJpegSizes();
1636         for (i = 0; i < availablePictureSizes.size(); i++) {
1637             if ((availablePictureSizes[i].width ==
1638                     validatedParams.pictureWidth) &&
1639                 (availablePictureSizes[i].height ==
1640                     validatedParams.pictureHeight)) break;
1641         }
1642         if (i == availablePictureSizes.size()) {
1643             ALOGE("%s: Requested picture size %d x %d is not supported",
1644                     __FUNCTION__, validatedParams.pictureWidth,
1645                     validatedParams.pictureHeight);
1646             return BAD_VALUE;
1647         }
1648     }
1649 
1650     // JPEG_THUMBNAIL_WIDTH/HEIGHT
1651     validatedParams.jpegThumbSize[0] =
1652             newParams.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
1653     validatedParams.jpegThumbSize[1] =
1654             newParams.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
1655     if (validatedParams.jpegThumbSize[0] != jpegThumbSize[0] ||
1656             validatedParams.jpegThumbSize[1] != jpegThumbSize[1]) {
1657         camera_metadata_ro_entry_t availableJpegThumbSizes =
1658             staticInfo(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1659         for (i = 0; i < availableJpegThumbSizes.count; i+=2) {
1660             if ((availableJpegThumbSizes.data.i32[i] ==
1661                     validatedParams.jpegThumbSize[0]) &&
1662                 (availableJpegThumbSizes.data.i32[i+1] ==
1663                     validatedParams.jpegThumbSize[1])) break;
1664         }
1665         if (i == availableJpegThumbSizes.count) {
1666             ALOGE("%s: Requested JPEG thumbnail size %d x %d is not supported",
1667                     __FUNCTION__, validatedParams.jpegThumbSize[0],
1668                     validatedParams.jpegThumbSize[1]);
1669             return BAD_VALUE;
1670         }
1671     }
1672 
1673     // JPEG_THUMBNAIL_QUALITY
1674     int quality = newParams.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY);
1675     // also makes sure quality fits in uint8_t
1676     if (quality < 0 || quality > 100) {
1677         ALOGE("%s: Requested JPEG thumbnail quality %d is not supported",
1678                 __FUNCTION__, quality);
1679         return BAD_VALUE;
1680     }
1681     validatedParams.jpegThumbQuality = quality;
1682 
1683     // JPEG_QUALITY
1684     quality = newParams.getInt(CameraParameters::KEY_JPEG_QUALITY);
1685     // also makes sure quality fits in uint8_t
1686     if (quality < 0 || quality > 100) {
1687         ALOGE("%s: Requested JPEG quality %d is not supported",
1688                 __FUNCTION__, quality);
1689         return BAD_VALUE;
1690     }
1691     validatedParams.jpegQuality = quality;
1692 
1693     // ROTATION
1694     validatedParams.jpegRotation =
1695             newParams.getInt(CameraParameters::KEY_ROTATION);
1696     if (validatedParams.jpegRotation != 0 &&
1697             validatedParams.jpegRotation != 90 &&
1698             validatedParams.jpegRotation != 180 &&
1699             validatedParams.jpegRotation != 270) {
1700         ALOGE("%s: Requested picture rotation angle %d is not supported",
1701                 __FUNCTION__, validatedParams.jpegRotation);
1702         return BAD_VALUE;
1703     }
1704 
1705     // GPS
1706 
1707     const char *gpsLatStr =
1708             newParams.get(CameraParameters::KEY_GPS_LATITUDE);
1709     if (gpsLatStr != NULL) {
1710         const char *gpsLongStr =
1711                 newParams.get(CameraParameters::KEY_GPS_LONGITUDE);
1712         const char *gpsAltitudeStr =
1713                 newParams.get(CameraParameters::KEY_GPS_ALTITUDE);
1714         const char *gpsTimeStr =
1715                 newParams.get(CameraParameters::KEY_GPS_TIMESTAMP);
1716         const char *gpsProcMethodStr =
1717                 newParams.get(CameraParameters::KEY_GPS_PROCESSING_METHOD);
1718         if (gpsLongStr == NULL ||
1719                 gpsAltitudeStr == NULL ||
1720                 gpsTimeStr == NULL ||
1721                 gpsProcMethodStr == NULL) {
1722             ALOGE("%s: Incomplete set of GPS parameters provided",
1723                     __FUNCTION__);
1724             return BAD_VALUE;
1725         }
1726         char *endPtr;
1727         errno = 0;
1728         validatedParams.gpsCoordinates[0] = strtod(gpsLatStr, &endPtr);
1729         if (errno || endPtr == gpsLatStr) {
1730             ALOGE("%s: Malformed GPS latitude: %s", __FUNCTION__, gpsLatStr);
1731             return BAD_VALUE;
1732         }
1733         errno = 0;
1734         validatedParams.gpsCoordinates[1] = strtod(gpsLongStr, &endPtr);
1735         if (errno || endPtr == gpsLongStr) {
1736             ALOGE("%s: Malformed GPS longitude: %s", __FUNCTION__, gpsLongStr);
1737             return BAD_VALUE;
1738         }
1739         errno = 0;
1740         validatedParams.gpsCoordinates[2] = strtod(gpsAltitudeStr, &endPtr);
1741         if (errno || endPtr == gpsAltitudeStr) {
1742             ALOGE("%s: Malformed GPS altitude: %s", __FUNCTION__,
1743                     gpsAltitudeStr);
1744             return BAD_VALUE;
1745         }
1746         errno = 0;
1747         validatedParams.gpsTimestamp = strtoll(gpsTimeStr, &endPtr, 10);
1748         if (errno || endPtr == gpsTimeStr) {
1749             ALOGE("%s: Malformed GPS timestamp: %s", __FUNCTION__, gpsTimeStr);
1750             return BAD_VALUE;
1751         }
1752         validatedParams.gpsProcessingMethod = gpsProcMethodStr;
1753 
1754         validatedParams.gpsEnabled = true;
1755     } else {
1756         validatedParams.gpsEnabled = false;
1757     }
1758 
1759     // EFFECT
1760     validatedParams.effectMode = effectModeStringToEnum(
1761         newParams.get(CameraParameters::KEY_EFFECT) );
1762     if (validatedParams.effectMode != effectMode) {
1763         camera_metadata_ro_entry_t availableEffectModes =
1764             staticInfo(ANDROID_CONTROL_AVAILABLE_EFFECTS);
1765         for (i = 0; i < availableEffectModes.count; i++) {
1766             if (validatedParams.effectMode == availableEffectModes.data.u8[i]) break;
1767         }
1768         if (i == availableEffectModes.count) {
1769             ALOGE("%s: Requested effect mode \"%s\" is not supported",
1770                     __FUNCTION__,
1771                     newParams.get(CameraParameters::KEY_EFFECT) );
1772             return BAD_VALUE;
1773         }
1774     }
1775 
1776     // ANTIBANDING
1777     validatedParams.antibandingMode = abModeStringToEnum(
1778         newParams.get(CameraParameters::KEY_ANTIBANDING) );
1779     if (validatedParams.antibandingMode != antibandingMode) {
1780         camera_metadata_ro_entry_t availableAbModes =
1781             staticInfo(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES);
1782         for (i = 0; i < availableAbModes.count; i++) {
1783             if (validatedParams.antibandingMode == availableAbModes.data.u8[i])
1784                 break;
1785         }
1786         if (i == availableAbModes.count) {
1787             ALOGE("%s: Requested antibanding mode \"%s\" is not supported",
1788                     __FUNCTION__,
1789                     newParams.get(CameraParameters::KEY_ANTIBANDING));
1790             return BAD_VALUE;
1791         }
1792     }
1793 
1794     // SCENE_MODE
1795     validatedParams.sceneMode = sceneModeStringToEnum(
1796         newParams.get(CameraParameters::KEY_SCENE_MODE), mDefaultSceneMode);
1797     if (validatedParams.sceneMode != sceneMode &&
1798             validatedParams.sceneMode !=
1799             ANDROID_CONTROL_SCENE_MODE_DISABLED) {
1800         camera_metadata_ro_entry_t availableSceneModes =
1801             staticInfo(ANDROID_CONTROL_AVAILABLE_SCENE_MODES);
1802         for (i = 0; i < availableSceneModes.count; i++) {
1803             if (validatedParams.sceneMode == availableSceneModes.data.u8[i])
1804                 break;
1805         }
1806         if (i == availableSceneModes.count) {
1807             ALOGE("%s: Requested scene mode \"%s\" is not supported",
1808                     __FUNCTION__,
1809                     newParams.get(CameraParameters::KEY_SCENE_MODE));
1810             return BAD_VALUE;
1811         }
1812     }
1813     bool sceneModeSet =
1814             validatedParams.sceneMode != mDefaultSceneMode;
1815 
1816     // FLASH_MODE
1817     if (sceneModeSet) {
1818         validatedParams.flashMode =
1819                 fastInfo.sceneModeOverrides.
1820                         valueFor(validatedParams.sceneMode).flashMode;
1821     } else {
1822         validatedParams.flashMode = FLASH_MODE_INVALID;
1823     }
1824     if (validatedParams.flashMode == FLASH_MODE_INVALID) {
1825         validatedParams.flashMode = flashModeStringToEnum(
1826             newParams.get(CameraParameters::KEY_FLASH_MODE) );
1827     }
1828 
1829     if (validatedParams.flashMode != flashMode) {
1830         camera_metadata_ro_entry_t flashAvailable =
1831             staticInfo(ANDROID_FLASH_INFO_AVAILABLE, 1, 1);
1832         bool isFlashAvailable =
1833                 flashAvailable.data.u8[0] == ANDROID_FLASH_INFO_AVAILABLE_TRUE;
1834         if (!isFlashAvailable &&
1835                 validatedParams.flashMode != Parameters::FLASH_MODE_OFF) {
1836             ALOGE("%s: Requested flash mode \"%s\" is not supported: "
1837                     "No flash on device", __FUNCTION__,
1838                     newParams.get(CameraParameters::KEY_FLASH_MODE));
1839             return BAD_VALUE;
1840         } else if (validatedParams.flashMode == Parameters::FLASH_MODE_RED_EYE) {
1841             camera_metadata_ro_entry_t availableAeModes =
1842                 staticInfo(ANDROID_CONTROL_AE_AVAILABLE_MODES);
1843             for (i = 0; i < availableAeModes.count; i++) {
1844                 if (validatedParams.flashMode == availableAeModes.data.u8[i])
1845                     break;
1846             }
1847             if (i == availableAeModes.count) {
1848                 ALOGE("%s: Requested flash mode \"%s\" is not supported",
1849                         __FUNCTION__,
1850                         newParams.get(CameraParameters::KEY_FLASH_MODE));
1851                 return BAD_VALUE;
1852             }
1853         } else if (validatedParams.flashMode == -1) {
1854             ALOGE("%s: Requested flash mode \"%s\" is unknown",
1855                     __FUNCTION__,
1856                     newParams.get(CameraParameters::KEY_FLASH_MODE));
1857             return BAD_VALUE;
1858         }
1859         // Update in case of override, but only if flash is supported
1860         if (isFlashAvailable) {
1861             newParams.set(CameraParameters::KEY_FLASH_MODE,
1862                     flashModeEnumToString(validatedParams.flashMode));
1863         }
1864     }
1865 
1866     // WHITE_BALANCE
1867     if (sceneModeSet) {
1868         validatedParams.wbMode =
1869                 fastInfo.sceneModeOverrides.
1870                         valueFor(validatedParams.sceneMode).wbMode;
1871     } else {
1872         validatedParams.wbMode = ANDROID_CONTROL_AWB_MODE_OFF;
1873     }
1874     if (validatedParams.wbMode == ANDROID_CONTROL_AWB_MODE_OFF) {
1875         validatedParams.wbMode = wbModeStringToEnum(
1876             newParams.get(CameraParameters::KEY_WHITE_BALANCE) );
1877     }
1878     if (validatedParams.wbMode != wbMode) {
1879         camera_metadata_ro_entry_t availableWbModes =
1880             staticInfo(ANDROID_CONTROL_AWB_AVAILABLE_MODES, 0, 0, false);
1881         for (i = 0; i < availableWbModes.count; i++) {
1882             if (validatedParams.wbMode == availableWbModes.data.u8[i]) break;
1883         }
1884         if (i == availableWbModes.count) {
1885             ALOGE("%s: Requested white balance mode %s is not supported",
1886                     __FUNCTION__,
1887                     newParams.get(CameraParameters::KEY_WHITE_BALANCE));
1888             return BAD_VALUE;
1889         }
1890         // Update in case of override
1891         newParams.set(CameraParameters::KEY_WHITE_BALANCE,
1892                 wbModeEnumToString(validatedParams.wbMode));
1893     }
1894 
1895     // FOCUS_MODE
1896     if (sceneModeSet) {
1897         validatedParams.focusMode =
1898                 fastInfo.sceneModeOverrides.
1899                         valueFor(validatedParams.sceneMode).focusMode;
1900     } else {
1901         validatedParams.focusMode = FOCUS_MODE_INVALID;
1902     }
1903     if (validatedParams.focusMode == FOCUS_MODE_INVALID) {
1904         validatedParams.focusMode = focusModeStringToEnum(
1905                 newParams.get(CameraParameters::KEY_FOCUS_MODE) );
1906     }
1907     if (validatedParams.focusMode != focusMode) {
1908         validatedParams.currentAfTriggerId = -1;
1909         if (validatedParams.focusMode != Parameters::FOCUS_MODE_FIXED) {
1910             camera_metadata_ro_entry_t minFocusDistance =
1911                 staticInfo(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE, 0, 0,
1912                         false);
1913             if (minFocusDistance.count && minFocusDistance.data.f[0] == 0) {
1914                 ALOGE("%s: Requested focus mode \"%s\" is not available: "
1915                         "fixed focus lens",
1916                         __FUNCTION__,
1917                         newParams.get(CameraParameters::KEY_FOCUS_MODE));
1918                 return BAD_VALUE;
1919             } else if (validatedParams.focusMode !=
1920                     Parameters::FOCUS_MODE_INFINITY) {
1921                 camera_metadata_ro_entry_t availableFocusModes =
1922                     staticInfo(ANDROID_CONTROL_AF_AVAILABLE_MODES);
1923                 for (i = 0; i < availableFocusModes.count; i++) {
1924                     if (validatedParams.focusMode ==
1925                             availableFocusModes.data.u8[i]) break;
1926                 }
1927                 if (i == availableFocusModes.count) {
1928                     ALOGE("%s: Requested focus mode \"%s\" is not supported",
1929                             __FUNCTION__,
1930                             newParams.get(CameraParameters::KEY_FOCUS_MODE));
1931                     return BAD_VALUE;
1932                 }
1933             }
1934         }
1935         validatedParams.focusState = ANDROID_CONTROL_AF_STATE_INACTIVE;
1936         // Always reset shadow focus mode to avoid reverting settings
1937         validatedParams.shadowFocusMode = FOCUS_MODE_INVALID;
1938         // Update in case of override
1939         newParams.set(CameraParameters::KEY_FOCUS_MODE,
1940                 focusModeEnumToString(validatedParams.focusMode));
1941     } else {
1942         validatedParams.currentAfTriggerId = currentAfTriggerId;
1943     }
1944 
1945     // FOCUS_AREAS
1946     res = parseAreas(newParams.get(CameraParameters::KEY_FOCUS_AREAS),
1947             &validatedParams.focusingAreas);
1948     size_t maxAfRegions = (size_t)staticInfo(ANDROID_CONTROL_MAX_REGIONS,
1949               Parameters::NUM_REGION, Parameters::NUM_REGION).
1950               data.i32[Parameters::REGION_AF];
1951     if (res == OK) res = validateAreas(validatedParams.focusingAreas,
1952             maxAfRegions, AREA_KIND_FOCUS);
1953     if (res != OK) {
1954         ALOGE("%s: Requested focus areas are malformed: %s",
1955                 __FUNCTION__, newParams.get(CameraParameters::KEY_FOCUS_AREAS));
1956         return BAD_VALUE;
1957     }
1958 
1959     // EXPOSURE_COMPENSATION
1960     validatedParams.exposureCompensation =
1961         newParams.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION);
1962     camera_metadata_ro_entry_t exposureCompensationRange =
1963         staticInfo(ANDROID_CONTROL_AE_COMPENSATION_RANGE);
1964     if ((validatedParams.exposureCompensation <
1965             exposureCompensationRange.data.i32[0]) ||
1966         (validatedParams.exposureCompensation >
1967             exposureCompensationRange.data.i32[1])) {
1968         ALOGE("%s: Requested exposure compensation index is out of bounds: %d",
1969                 __FUNCTION__, validatedParams.exposureCompensation);
1970         return BAD_VALUE;
1971     }
1972 
1973     if (autoExposureLockAvailable) {
1974         validatedParams.autoExposureLock = boolFromString(
1975             newParams.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK));
1976     } else if (nullptr !=
1977             newParams.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK)){
1978         ALOGE("%s: Requested auto exposure lock is not supported",
1979               __FUNCTION__);
1980         return BAD_VALUE;
1981     }
1982 
1983     if (autoWhiteBalanceLockAvailable) {
1984         validatedParams.autoWhiteBalanceLock = boolFromString(
1985                 newParams.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK));
1986     } else if (nullptr !=
1987            newParams.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK)) {
1988         ALOGE("%s: Requested auto whitebalance lock is not supported",
1989               __FUNCTION__);
1990         return BAD_VALUE;
1991     }
1992 
1993     // METERING_AREAS
1994     size_t maxAeRegions = (size_t)staticInfo(ANDROID_CONTROL_MAX_REGIONS,
1995             Parameters::NUM_REGION, Parameters::NUM_REGION).
1996             data.i32[Parameters::REGION_AE];
1997     res = parseAreas(newParams.get(CameraParameters::KEY_METERING_AREAS),
1998             &validatedParams.meteringAreas);
1999     if (res == OK) {
2000         res = validateAreas(validatedParams.meteringAreas, maxAeRegions,
2001                             AREA_KIND_METERING);
2002     }
2003     if (res != OK) {
2004         ALOGE("%s: Requested metering areas are malformed: %s",
2005                 __FUNCTION__,
2006                 newParams.get(CameraParameters::KEY_METERING_AREAS));
2007         return BAD_VALUE;
2008     }
2009 
2010     // ZOOM
2011     if (zoomAvailable) {
2012         validatedParams.zoom = newParams.getInt(CameraParameters::KEY_ZOOM);
2013         if (validatedParams.zoom < 0
2014                     || validatedParams.zoom >= (int)NUM_ZOOM_STEPS) {
2015             ALOGE("%s: Requested zoom level %d is not supported",
2016                     __FUNCTION__, validatedParams.zoom);
2017             return BAD_VALUE;
2018         }
2019     }
2020 
2021     // VIDEO_SIZE
2022     newParams.getVideoSize(&validatedParams.videoWidth,
2023             &validatedParams.videoHeight);
2024     if (validatedParams.videoWidth != videoWidth ||
2025             validatedParams.videoHeight != videoHeight) {
2026         if (state == RECORD) {
2027             ALOGW("%s: Video size cannot be updated (from %d x %d to %d x %d)"
2028                     " when recording is active! Ignore the size update!",
2029                     __FUNCTION__, videoWidth, videoHeight, validatedParams.videoWidth,
2030                     validatedParams.videoHeight);
2031             validatedParams.videoWidth = videoWidth;
2032             validatedParams.videoHeight = videoHeight;
2033             newParams.setVideoSize(videoWidth, videoHeight);
2034         } else {
2035             for (i = 0; i < availableVideoSizes.size(); i++) {
2036                 if ((availableVideoSizes[i].width ==
2037                         validatedParams.videoWidth) &&
2038                     (availableVideoSizes[i].height ==
2039                         validatedParams.videoHeight)) break;
2040             }
2041             if (i == availableVideoSizes.size()) {
2042                 ALOGE("%s: Requested video size %d x %d is not supported",
2043                         __FUNCTION__, validatedParams.videoWidth,
2044                         validatedParams.videoHeight);
2045                 return BAD_VALUE;
2046             }
2047         }
2048     }
2049 
2050     // VIDEO_STABILIZATION
2051     validatedParams.videoStabilization = boolFromString(
2052         newParams.get(CameraParameters::KEY_VIDEO_STABILIZATION) );
2053     camera_metadata_ro_entry_t availableVideoStabilizationModes =
2054         staticInfo(ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES, 0, 0,
2055                 false);
2056     if (validatedParams.videoStabilization &&
2057             availableVideoStabilizationModes.count == 1) {
2058         ALOGE("%s: Video stabilization not supported", __FUNCTION__);
2059     }
2060 
2061     /** Update internal parameters */
2062 
2063     *this = validatedParams;
2064     updateOverriddenJpegSize();
2065 
2066     /** Update external parameters calculated from the internal ones */
2067 
2068     // HORIZONTAL/VERTICAL FIELD OF VIEW
2069     float horizFov, vertFov;
2070     res = calculatePictureFovs(&horizFov, &vertFov);
2071     if (res != OK) {
2072         ALOGE("%s: Can't calculate FOVs", __FUNCTION__);
2073         // continue so parameters are at least consistent
2074     }
2075     newParams.setFloat(CameraParameters::KEY_HORIZONTAL_VIEW_ANGLE,
2076             horizFov);
2077     newParams.setFloat(CameraParameters::KEY_VERTICAL_VIEW_ANGLE,
2078             vertFov);
2079     ALOGV("Current still picture FOV: %f x %f deg", horizFov, vertFov);
2080 
2081     // Need to flatten again in case of overrides
2082     paramsFlattened = newParams.flatten();
2083     params = newParams;
2084 
2085     slowJpegMode = isSlowJpegModeForced;
2086     Size pictureSize = { pictureWidth, pictureHeight };
2087     bool zslFrameRateSupported = false;
2088     int64_t jpegMinFrameDurationNs = getJpegStreamMinFrameDurationNs(pictureSize);
2089     if (previewFpsRange[1] > 1e9/jpegMinFrameDurationNs + FPS_MARGIN) {
2090         slowJpegMode = true;
2091     }
2092     if (isZslReprocessPresent) {
2093         unsigned int firstApiLevel =
2094             android::base::GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
2095         Size chosenSize;
2096         if ((firstApiLevel >= __ANDROID_API_S__) &&
2097             !android::base::GetBoolProperty("ro.camera.enableCamera1MaxZsl", false)) {
2098             chosenSize = pictureSize;
2099         } else {
2100           // follow old behavior of keeping max zsl size as the input / output
2101           // zsl stream size
2102           chosenSize = fastInfo.maxZslSize;
2103         }
2104         int64_t zslMinFrameDurationNs = getZslStreamMinFrameDurationNs(chosenSize);
2105         if (zslMinFrameDurationNs > 0 &&
2106                 previewFpsRange[1] <= (1e9/zslMinFrameDurationNs + FPS_MARGIN)) {
2107             zslFrameRateSupported = true;
2108             fastInfo.usedZslSize = chosenSize;
2109         }
2110     }
2111 
2112     if (isDeviceZslSupported || slowJpegMode || !zslFrameRateSupported ||
2113             android::base::GetBoolProperty("camera.disable_zsl_mode", false)) {
2114         allowZslMode = false;
2115     } else {
2116         allowZslMode = isZslReprocessPresent;
2117     }
2118     ALOGV("%s: allowZslMode: %d slowJpegMode %d", __FUNCTION__, allowZslMode, slowJpegMode);
2119 
2120     return OK;
2121 }
2122 
updateRequest(CameraMetadata * request) const2123 status_t Parameters::updateRequest(CameraMetadata *request) const {
2124     ATRACE_CALL();
2125     status_t res;
2126 
2127     /**
2128      * Mixin default important security values
2129      * - android.led.transmit = defaulted ON
2130      */
2131     camera_metadata_ro_entry_t entry = staticInfo(ANDROID_LED_AVAILABLE_LEDS,
2132                                                   /*minimumCount*/0,
2133                                                   /*maximumCount*/0,
2134                                                   /*required*/false);
2135     for(size_t i = 0; i < entry.count; ++i) {
2136         uint8_t led = entry.data.u8[i];
2137 
2138         switch(led) {
2139             // Transmit LED is unconditionally on when using
2140             // the android.hardware.Camera API
2141             case ANDROID_LED_AVAILABLE_LEDS_TRANSMIT: {
2142                 uint8_t transmitDefault = ANDROID_LED_TRANSMIT_ON;
2143                 res = request->update(ANDROID_LED_TRANSMIT,
2144                                       &transmitDefault, 1);
2145                 if (res != OK) return res;
2146                 break;
2147             }
2148         }
2149     }
2150 
2151     /**
2152      * Construct metadata from parameters
2153      */
2154 
2155     uint8_t metadataMode = ANDROID_REQUEST_METADATA_MODE_FULL;
2156     res = request->update(ANDROID_REQUEST_METADATA_MODE,
2157             &metadataMode, 1);
2158     if (res != OK) return res;
2159 
2160     camera_metadata_entry_t intent =
2161             request->find(ANDROID_CONTROL_CAPTURE_INTENT);
2162 
2163     if (intent.count == 0) return BAD_VALUE;
2164 
2165     uint8_t distortionMode = ANDROID_DISTORTION_CORRECTION_MODE_OFF;
2166     if (intent.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE) {
2167         res = request->update(ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
2168                 fastInfo.bestStillCaptureFpsRange, 2);
2169         distortionMode = ANDROID_DISTORTION_CORRECTION_MODE_HIGH_QUALITY;
2170     } else {
2171         res = request->update(ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
2172                 previewFpsRange, 2);
2173         distortionMode = ANDROID_DISTORTION_CORRECTION_MODE_FAST;
2174     }
2175     if (res != OK) return res;
2176 
2177     if (isDistortionCorrectionSupported) {
2178         res = request->update(ANDROID_DISTORTION_CORRECTION_MODE,
2179                 &distortionMode, 1);
2180         if (res != OK) return res;
2181     }
2182 
2183     if (autoWhiteBalanceLockAvailable) {
2184         uint8_t reqWbLock = autoWhiteBalanceLock ?
2185                 ANDROID_CONTROL_AWB_LOCK_ON : ANDROID_CONTROL_AWB_LOCK_OFF;
2186         res = request->update(ANDROID_CONTROL_AWB_LOCK,
2187                 &reqWbLock, 1);
2188     }
2189 
2190     res = request->update(ANDROID_CONTROL_EFFECT_MODE,
2191             &effectMode, 1);
2192     if (res != OK) return res;
2193     res = request->update(ANDROID_CONTROL_AE_ANTIBANDING_MODE,
2194             &antibandingMode, 1);
2195     if (res != OK) return res;
2196 
2197     // android.hardware.Camera requires that when face detect is enabled, the
2198     // camera is in a face-priority mode. HAL3.x splits this into separate parts
2199     // (face detection statistics and face priority scene mode). Map from other
2200     // to the other.
2201     bool sceneModeActive =
2202             sceneMode != (uint8_t)ANDROID_CONTROL_SCENE_MODE_DISABLED;
2203     uint8_t reqControlMode = ANDROID_CONTROL_MODE_AUTO;
2204     if (enableFaceDetect || sceneModeActive) {
2205         reqControlMode = ANDROID_CONTROL_MODE_USE_SCENE_MODE;
2206     }
2207     res = request->update(ANDROID_CONTROL_MODE,
2208             &reqControlMode, 1);
2209     if (res != OK) return res;
2210 
2211     uint8_t reqSceneMode =
2212             sceneModeActive ? sceneMode :
2213             enableFaceDetect ? (uint8_t)ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY :
2214             mDefaultSceneMode;
2215     res = request->update(ANDROID_CONTROL_SCENE_MODE,
2216             &reqSceneMode, 1);
2217     if (res != OK) return res;
2218 
2219     uint8_t reqFlashMode = ANDROID_FLASH_MODE_OFF;
2220     uint8_t reqAeMode = ANDROID_CONTROL_AE_MODE_OFF;
2221     switch (flashMode) {
2222         case Parameters::FLASH_MODE_OFF:
2223             reqAeMode = ANDROID_CONTROL_AE_MODE_ON; break;
2224         case Parameters::FLASH_MODE_AUTO:
2225             reqAeMode = ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH; break;
2226         case Parameters::FLASH_MODE_ON:
2227             reqAeMode = ANDROID_CONTROL_AE_MODE_ON_ALWAYS_FLASH; break;
2228         case Parameters::FLASH_MODE_TORCH:
2229             reqAeMode = ANDROID_CONTROL_AE_MODE_ON;
2230             reqFlashMode = ANDROID_FLASH_MODE_TORCH;
2231             break;
2232         case Parameters::FLASH_MODE_RED_EYE:
2233             reqAeMode = ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE; break;
2234         default:
2235             ALOGE("%s: Camera %d: Unknown flash mode %d", __FUNCTION__,
2236                     cameraId, flashMode);
2237                 return BAD_VALUE;
2238     }
2239     res = request->update(ANDROID_FLASH_MODE,
2240             &reqFlashMode, 1);
2241     if (res != OK) return res;
2242     res = request->update(ANDROID_CONTROL_AE_MODE,
2243             &reqAeMode, 1);
2244     if (res != OK) return res;
2245 
2246     if (autoExposureLockAvailable) {
2247         uint8_t reqAeLock = autoExposureLock ?
2248                 ANDROID_CONTROL_AE_LOCK_ON : ANDROID_CONTROL_AE_LOCK_OFF;
2249         res = request->update(ANDROID_CONTROL_AE_LOCK,
2250                 &reqAeLock, 1);
2251         if (res != OK) return res;
2252     }
2253 
2254     res = request->update(ANDROID_CONTROL_AWB_MODE,
2255             &wbMode, 1);
2256     if (res != OK) return res;
2257 
2258     float reqFocusDistance = 0; // infinity focus in diopters
2259     uint8_t reqFocusMode = ANDROID_CONTROL_AF_MODE_OFF;
2260     switch (focusMode) {
2261         case Parameters::FOCUS_MODE_AUTO:
2262         case Parameters::FOCUS_MODE_MACRO:
2263         case Parameters::FOCUS_MODE_CONTINUOUS_VIDEO:
2264         case Parameters::FOCUS_MODE_CONTINUOUS_PICTURE:
2265         case Parameters::FOCUS_MODE_EDOF:
2266             reqFocusMode = focusMode;
2267             break;
2268         case Parameters::FOCUS_MODE_INFINITY:
2269         case Parameters::FOCUS_MODE_FIXED:
2270             reqFocusMode = ANDROID_CONTROL_AF_MODE_OFF;
2271             break;
2272         default:
2273                 ALOGE("%s: Camera %d: Unknown focus mode %d", __FUNCTION__,
2274                         cameraId, focusMode);
2275                 return BAD_VALUE;
2276     }
2277     res = request->update(ANDROID_LENS_FOCUS_DISTANCE,
2278             &reqFocusDistance, 1);
2279     if (res != OK) return res;
2280     res = request->update(ANDROID_CONTROL_AF_MODE,
2281             &reqFocusMode, 1);
2282     if (res != OK) return res;
2283 
2284     size_t reqFocusingAreasSize = focusingAreas.size() * 5;
2285     int32_t *reqFocusingAreas = new int32_t[reqFocusingAreasSize];
2286     for (size_t i = 0, j = 0; i < reqFocusingAreasSize; i += 5, j++) {
2287         if (focusingAreas[j].weight != 0) {
2288             reqFocusingAreas[i + 0] =
2289                     normalizedXToArray(focusingAreas[j].left);
2290             reqFocusingAreas[i + 1] =
2291                     normalizedYToArray(focusingAreas[j].top);
2292             reqFocusingAreas[i + 2] =
2293                     normalizedXToArray(focusingAreas[j].right);
2294             reqFocusingAreas[i + 3] =
2295                     normalizedYToArray(focusingAreas[j].bottom);
2296         } else {
2297             reqFocusingAreas[i + 0] = 0;
2298             reqFocusingAreas[i + 1] = 0;
2299             reqFocusingAreas[i + 2] = 0;
2300             reqFocusingAreas[i + 3] = 0;
2301         }
2302         reqFocusingAreas[i + 4] = focusingAreas[j].weight;
2303     }
2304     res = request->update(ANDROID_CONTROL_AF_REGIONS,
2305             reqFocusingAreas, reqFocusingAreasSize);
2306     if (res != OK) return res;
2307     delete[] reqFocusingAreas;
2308 
2309     res = request->update(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION,
2310             &exposureCompensation, 1);
2311     if (res != OK) return res;
2312 
2313     size_t reqMeteringAreasSize = meteringAreas.size() * 5;
2314     int32_t *reqMeteringAreas = new int32_t[reqMeteringAreasSize];
2315     for (size_t i = 0, j = 0; i < reqMeteringAreasSize; i += 5, j++) {
2316         if (meteringAreas[j].weight != 0) {
2317             reqMeteringAreas[i + 0] =
2318                 normalizedXToArray(meteringAreas[j].left);
2319             reqMeteringAreas[i + 1] =
2320                 normalizedYToArray(meteringAreas[j].top);
2321             reqMeteringAreas[i + 2] =
2322                 normalizedXToArray(meteringAreas[j].right);
2323             reqMeteringAreas[i + 3] =
2324                 normalizedYToArray(meteringAreas[j].bottom);
2325             // Requested size may be zero by rounding error with/without zooming.
2326             // The ae regions should be at least 1 if metering width/height is not zero.
2327             if (reqMeteringAreas[i + 0] == reqMeteringAreas[i + 2]) {
2328                 reqMeteringAreas[i + 2]++;
2329             }
2330             if (reqMeteringAreas[i + 1] == reqMeteringAreas[i + 3]) {
2331                 reqMeteringAreas[i + 3]++;
2332             }
2333         } else {
2334             reqMeteringAreas[i + 0] = 0;
2335             reqMeteringAreas[i + 1] = 0;
2336             reqMeteringAreas[i + 2] = 0;
2337             reqMeteringAreas[i + 3] = 0;
2338         }
2339         reqMeteringAreas[i + 4] = meteringAreas[j].weight;
2340     }
2341     res = request->update(ANDROID_CONTROL_AE_REGIONS,
2342             reqMeteringAreas, reqMeteringAreasSize);
2343     if (res != OK) return res;
2344 
2345     // Set awb regions to be the same as the metering regions if allowed
2346     size_t maxAwbRegions = (size_t)staticInfo(ANDROID_CONTROL_MAX_REGIONS,
2347             Parameters::NUM_REGION, Parameters::NUM_REGION).
2348             data.i32[Parameters::REGION_AWB];
2349     if (maxAwbRegions > 0) {
2350         if (maxAwbRegions >= meteringAreas.size()) {
2351             res = request->update(ANDROID_CONTROL_AWB_REGIONS,
2352                     reqMeteringAreas, reqMeteringAreasSize);
2353         } else {
2354             // Ensure the awb regions are zeroed if the region count is too high.
2355             int32_t zeroedAwbAreas[5] = {0, 0, 0, 0, 0};
2356             res = request->update(ANDROID_CONTROL_AWB_REGIONS,
2357                     zeroedAwbAreas, sizeof(zeroedAwbAreas)/sizeof(int32_t));
2358         }
2359         if (res != OK) return res;
2360     }
2361 
2362     delete[] reqMeteringAreas;
2363 
2364     CropRegion crop = calculateCropRegion(/*previewOnly*/ false);
2365     int32_t reqCropRegion[4] = {
2366         static_cast<int32_t>(crop.left),
2367         static_cast<int32_t>(crop.top),
2368         static_cast<int32_t>(crop.width),
2369         static_cast<int32_t>(crop.height)
2370     };
2371     res = request->update(ANDROID_SCALER_CROP_REGION,
2372             reqCropRegion, 4);
2373     if (res != OK) return res;
2374 
2375     uint8_t reqVstabMode = videoStabilization ?
2376             ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_ON :
2377             ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2378     res = request->update(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
2379             &reqVstabMode, 1);
2380     if (res != OK) return res;
2381 
2382     uint8_t reqFaceDetectMode = enableFaceDetect ?
2383             fastInfo.bestFaceDetectMode :
2384             (uint8_t)ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2385     res = request->update(ANDROID_STATISTICS_FACE_DETECT_MODE,
2386             &reqFaceDetectMode, 1);
2387     if (res != OK) return res;
2388 
2389     return OK;
2390 }
2391 
updateRequestJpeg(CameraMetadata * request) const2392 status_t Parameters::updateRequestJpeg(CameraMetadata *request) const {
2393     status_t res;
2394 
2395     res = request->update(ANDROID_JPEG_THUMBNAIL_SIZE,
2396             jpegThumbSize, 2);
2397     if (res != OK) return res;
2398     res = request->update(ANDROID_JPEG_THUMBNAIL_QUALITY,
2399             &jpegThumbQuality, 1);
2400     if (res != OK) return res;
2401     res = request->update(ANDROID_JPEG_QUALITY,
2402             &jpegQuality, 1);
2403     if (res != OK) return res;
2404     res = request->update(
2405             ANDROID_JPEG_ORIENTATION,
2406             &jpegRotation, 1);
2407     if (res != OK) return res;
2408 
2409     if (gpsEnabled) {
2410         res = request->update(
2411                 ANDROID_JPEG_GPS_COORDINATES,
2412                 gpsCoordinates, 3);
2413         if (res != OK) return res;
2414         res = request->update(
2415                 ANDROID_JPEG_GPS_TIMESTAMP,
2416                 &gpsTimestamp, 1);
2417         if (res != OK) return res;
2418         res = request->update(
2419                 ANDROID_JPEG_GPS_PROCESSING_METHOD,
2420                 gpsProcessingMethod);
2421         if (res != OK) return res;
2422     } else {
2423         res = request->erase(ANDROID_JPEG_GPS_COORDINATES);
2424         if (res != OK) return res;
2425         res = request->erase(ANDROID_JPEG_GPS_TIMESTAMP);
2426         if (res != OK) return res;
2427         res = request->erase(ANDROID_JPEG_GPS_PROCESSING_METHOD);
2428         if (res != OK) return res;
2429     }
2430     return OK;
2431 }
2432 
overrideJpegSizeByVideoSize()2433 status_t Parameters::overrideJpegSizeByVideoSize() {
2434     if (pictureSizeOverriden) {
2435         ALOGV("Picture size has been overridden. Skip overriding");
2436         return OK;
2437     }
2438 
2439     pictureSizeOverriden = true;
2440     pictureWidthLastSet = pictureWidth;
2441     pictureHeightLastSet = pictureHeight;
2442     pictureWidth = videoWidth;
2443     pictureHeight = videoHeight;
2444     // This change of picture size is invisible to app layer.
2445     // Do not update app visible params
2446     return OK;
2447 }
2448 
updateOverriddenJpegSize()2449 status_t Parameters::updateOverriddenJpegSize() {
2450     if (!pictureSizeOverriden) {
2451         ALOGV("Picture size has not been overridden. Skip checking");
2452         return OK;
2453     }
2454 
2455     pictureWidthLastSet = pictureWidth;
2456     pictureHeightLastSet = pictureHeight;
2457 
2458     if (pictureWidth <= videoWidth && pictureHeight <= videoHeight) {
2459         // Picture size is now smaller than video size. No need to override anymore
2460         return recoverOverriddenJpegSize();
2461     }
2462 
2463     pictureWidth = videoWidth;
2464     pictureHeight = videoHeight;
2465 
2466     return OK;
2467 }
2468 
recoverOverriddenJpegSize()2469 status_t Parameters::recoverOverriddenJpegSize() {
2470     if (!pictureSizeOverriden) {
2471         ALOGV("Picture size has not been overridden. Skip recovering");
2472         return OK;
2473     }
2474     pictureSizeOverriden = false;
2475     pictureWidth = pictureWidthLastSet;
2476     pictureHeight = pictureHeightLastSet;
2477     return OK;
2478 }
2479 
isJpegSizeOverridden()2480 bool Parameters::isJpegSizeOverridden() {
2481     return pictureSizeOverriden;
2482 }
2483 
useZeroShutterLag() const2484 bool Parameters::useZeroShutterLag() const {
2485     // If ZSL mode is disabled, don't use it
2486     if (!allowZslMode) return false;
2487     // If recording hint is enabled, don't do ZSL
2488     if (recordingHint) return false;
2489     // If still capture size is no bigger than preview or video size,
2490     // don't do ZSL
2491     if (pictureWidth <= previewWidth || pictureHeight <= previewHeight ||
2492             pictureWidth <= videoWidth || pictureHeight <= videoHeight) {
2493         return false;
2494     }
2495     // If still capture size is less than quarter of max, don't do ZSL
2496     if ((pictureWidth * pictureHeight) <
2497             (fastInfo.maxJpegSize.width * fastInfo.maxJpegSize.height / 4) ) {
2498         return false;
2499     }
2500     return true;
2501 }
2502 
getDefaultFocalLength(CameraDeviceBase * device)2503 status_t Parameters::getDefaultFocalLength(CameraDeviceBase *device) {
2504     if (device == nullptr) {
2505         ALOGE("%s: Camera device is nullptr", __FUNCTION__);
2506         return BAD_VALUE;
2507     }
2508 
2509     camera_metadata_ro_entry_t hwLevel = staticInfo(ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL);
2510     if (!hwLevel.count) return NO_INIT;
2511     fastInfo.isExternalCamera =
2512             hwLevel.data.u8[0] == ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL;
2513 
2514     camera_metadata_ro_entry_t availableFocalLengths =
2515         staticInfo(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS, 0, 0, /*required*/false);
2516 
2517     // Find focal length in PREVIEW template to use as default focal length.
2518     if (availableFocalLengths.count) {
2519         // Find smallest (widest-angle) focal length to use as basis of still
2520         // picture FOV reporting.
2521         fastInfo.defaultFocalLength = availableFocalLengths.data.f[0];
2522         for (size_t i = 1; i < availableFocalLengths.count; i++) {
2523             if (fastInfo.defaultFocalLength > availableFocalLengths.data.f[i]) {
2524                 fastInfo.defaultFocalLength = availableFocalLengths.data.f[i];
2525             }
2526         }
2527 
2528         // Use focal length in preview template if it exists
2529         CameraMetadata previewTemplate;
2530         status_t res = device->createDefaultRequest(CAMERA_TEMPLATE_PREVIEW, &previewTemplate);
2531         if (res != OK) {
2532             ALOGE("%s: Failed to create default PREVIEW request: %s (%d)",
2533                     __FUNCTION__, strerror(-res), res);
2534             return res;
2535         }
2536         camera_metadata_entry entry = previewTemplate.find(ANDROID_LENS_FOCAL_LENGTH);
2537         if (entry.count != 0) {
2538             fastInfo.defaultFocalLength = entry.data.f[0];
2539         }
2540     } else if (fastInfo.isExternalCamera) {
2541         fastInfo.defaultFocalLength = -1.0;
2542     } else {
2543         return NO_INIT;
2544     }
2545     return OK;
2546 }
2547 
getStateName(State state)2548 const char* Parameters::getStateName(State state) {
2549 #define CASE_ENUM_TO_CHAR(x) case x: return(#x); break;
2550     switch(state) {
2551         CASE_ENUM_TO_CHAR(DISCONNECTED)
2552         CASE_ENUM_TO_CHAR(STOPPED)
2553         CASE_ENUM_TO_CHAR(WAITING_FOR_PREVIEW_WINDOW)
2554         CASE_ENUM_TO_CHAR(PREVIEW)
2555         CASE_ENUM_TO_CHAR(RECORD)
2556         CASE_ENUM_TO_CHAR(STILL_CAPTURE)
2557         CASE_ENUM_TO_CHAR(VIDEO_SNAPSHOT)
2558         default:
2559             return "Unknown state!";
2560             break;
2561     }
2562 #undef CASE_ENUM_TO_CHAR
2563 }
2564 
formatStringToEnum(const char * format)2565 int Parameters::formatStringToEnum(const char *format) {
2566     return CameraParameters::previewFormatToEnum(format);
2567 }
2568 
formatEnumToString(int format)2569 const char* Parameters::formatEnumToString(int format) {
2570     const char *fmt;
2571     switch(format) {
2572         case HAL_PIXEL_FORMAT_YCbCr_422_SP: // NV16
2573             fmt = CameraParameters::PIXEL_FORMAT_YUV422SP;
2574             break;
2575         case HAL_PIXEL_FORMAT_YCrCb_420_SP: // NV21
2576             fmt = CameraParameters::PIXEL_FORMAT_YUV420SP;
2577             break;
2578         case HAL_PIXEL_FORMAT_YCbCr_422_I: // YUY2
2579             fmt = CameraParameters::PIXEL_FORMAT_YUV422I;
2580             break;
2581         case HAL_PIXEL_FORMAT_YV12:        // YV12
2582             fmt = CameraParameters::PIXEL_FORMAT_YUV420P;
2583             break;
2584         case HAL_PIXEL_FORMAT_RGB_565:     // RGB565
2585             fmt = CameraParameters::PIXEL_FORMAT_RGB565;
2586             break;
2587         case HAL_PIXEL_FORMAT_RGBA_8888:   // RGBA8888
2588             fmt = CameraParameters::PIXEL_FORMAT_RGBA8888;
2589             break;
2590         case HAL_PIXEL_FORMAT_RAW16:
2591             ALOGW("Raw sensor preview format requested.");
2592             fmt = CameraParameters::PIXEL_FORMAT_BAYER_RGGB;
2593             break;
2594         default:
2595             ALOGE("%s: Unknown preview format: %x",
2596                     __FUNCTION__,  format);
2597             fmt = NULL;
2598             break;
2599     }
2600     return fmt;
2601 }
2602 
wbModeStringToEnum(const char * wbMode)2603 int Parameters::wbModeStringToEnum(const char *wbMode) {
2604     return
2605         !wbMode ?
2606             ANDROID_CONTROL_AWB_MODE_AUTO :
2607         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_AUTO) ?
2608             ANDROID_CONTROL_AWB_MODE_AUTO :
2609         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_INCANDESCENT) ?
2610             ANDROID_CONTROL_AWB_MODE_INCANDESCENT :
2611         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_FLUORESCENT) ?
2612             ANDROID_CONTROL_AWB_MODE_FLUORESCENT :
2613         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_WARM_FLUORESCENT) ?
2614             ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT :
2615         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_DAYLIGHT) ?
2616             ANDROID_CONTROL_AWB_MODE_DAYLIGHT :
2617         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT) ?
2618             ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT :
2619         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_TWILIGHT) ?
2620             ANDROID_CONTROL_AWB_MODE_TWILIGHT :
2621         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_SHADE) ?
2622             ANDROID_CONTROL_AWB_MODE_SHADE :
2623         -1;
2624 }
2625 
wbModeEnumToString(uint8_t wbMode)2626 const char* Parameters::wbModeEnumToString(uint8_t wbMode) {
2627     switch (wbMode) {
2628         case ANDROID_CONTROL_AWB_MODE_AUTO:
2629             return CameraParameters::WHITE_BALANCE_AUTO;
2630         case ANDROID_CONTROL_AWB_MODE_INCANDESCENT:
2631             return CameraParameters::WHITE_BALANCE_INCANDESCENT;
2632         case ANDROID_CONTROL_AWB_MODE_FLUORESCENT:
2633             return CameraParameters::WHITE_BALANCE_FLUORESCENT;
2634         case ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT:
2635             return CameraParameters::WHITE_BALANCE_WARM_FLUORESCENT;
2636         case ANDROID_CONTROL_AWB_MODE_DAYLIGHT:
2637             return CameraParameters::WHITE_BALANCE_DAYLIGHT;
2638         case ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT:
2639             return CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT;
2640         case ANDROID_CONTROL_AWB_MODE_TWILIGHT:
2641             return CameraParameters::WHITE_BALANCE_TWILIGHT;
2642         case ANDROID_CONTROL_AWB_MODE_SHADE:
2643             return CameraParameters::WHITE_BALANCE_SHADE;
2644         default:
2645             ALOGE("%s: Unknown AWB mode enum: %d",
2646                     __FUNCTION__, wbMode);
2647             return "unknown";
2648     }
2649 }
2650 
effectModeStringToEnum(const char * effectMode)2651 int Parameters::effectModeStringToEnum(const char *effectMode) {
2652     return
2653         !effectMode ?
2654             ANDROID_CONTROL_EFFECT_MODE_OFF :
2655         !strcmp(effectMode, CameraParameters::EFFECT_NONE) ?
2656             ANDROID_CONTROL_EFFECT_MODE_OFF :
2657         !strcmp(effectMode, CameraParameters::EFFECT_MONO) ?
2658             ANDROID_CONTROL_EFFECT_MODE_MONO :
2659         !strcmp(effectMode, CameraParameters::EFFECT_NEGATIVE) ?
2660             ANDROID_CONTROL_EFFECT_MODE_NEGATIVE :
2661         !strcmp(effectMode, CameraParameters::EFFECT_SOLARIZE) ?
2662             ANDROID_CONTROL_EFFECT_MODE_SOLARIZE :
2663         !strcmp(effectMode, CameraParameters::EFFECT_SEPIA) ?
2664             ANDROID_CONTROL_EFFECT_MODE_SEPIA :
2665         !strcmp(effectMode, CameraParameters::EFFECT_POSTERIZE) ?
2666             ANDROID_CONTROL_EFFECT_MODE_POSTERIZE :
2667         !strcmp(effectMode, CameraParameters::EFFECT_WHITEBOARD) ?
2668             ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD :
2669         !strcmp(effectMode, CameraParameters::EFFECT_BLACKBOARD) ?
2670             ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD :
2671         !strcmp(effectMode, CameraParameters::EFFECT_AQUA) ?
2672             ANDROID_CONTROL_EFFECT_MODE_AQUA :
2673         -1;
2674 }
2675 
abModeStringToEnum(const char * abMode)2676 int Parameters::abModeStringToEnum(const char *abMode) {
2677     return
2678         !abMode ?
2679             ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO :
2680         !strcmp(abMode, CameraParameters::ANTIBANDING_AUTO) ?
2681             ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO :
2682         !strcmp(abMode, CameraParameters::ANTIBANDING_OFF) ?
2683             ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF :
2684         !strcmp(abMode, CameraParameters::ANTIBANDING_50HZ) ?
2685             ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ :
2686         !strcmp(abMode, CameraParameters::ANTIBANDING_60HZ) ?
2687             ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ :
2688         -1;
2689 }
2690 
sceneModeStringToEnum(const char * sceneMode,uint8_t defaultSceneMode)2691 int Parameters::sceneModeStringToEnum(const char *sceneMode, uint8_t defaultSceneMode) {
2692     return
2693         !sceneMode ?
2694             defaultSceneMode :
2695         !strcmp(sceneMode, CameraParameters::SCENE_MODE_AUTO) ?
2696             defaultSceneMode :
2697         !strcmp(sceneMode, CameraParameters::SCENE_MODE_ACTION) ?
2698             ANDROID_CONTROL_SCENE_MODE_ACTION :
2699         !strcmp(sceneMode, CameraParameters::SCENE_MODE_PORTRAIT) ?
2700             ANDROID_CONTROL_SCENE_MODE_PORTRAIT :
2701         !strcmp(sceneMode, CameraParameters::SCENE_MODE_LANDSCAPE) ?
2702             ANDROID_CONTROL_SCENE_MODE_LANDSCAPE :
2703         !strcmp(sceneMode, CameraParameters::SCENE_MODE_NIGHT) ?
2704             ANDROID_CONTROL_SCENE_MODE_NIGHT :
2705         !strcmp(sceneMode, CameraParameters::SCENE_MODE_NIGHT_PORTRAIT) ?
2706             ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT :
2707         !strcmp(sceneMode, CameraParameters::SCENE_MODE_THEATRE) ?
2708             ANDROID_CONTROL_SCENE_MODE_THEATRE :
2709         !strcmp(sceneMode, CameraParameters::SCENE_MODE_BEACH) ?
2710             ANDROID_CONTROL_SCENE_MODE_BEACH :
2711         !strcmp(sceneMode, CameraParameters::SCENE_MODE_SNOW) ?
2712             ANDROID_CONTROL_SCENE_MODE_SNOW :
2713         !strcmp(sceneMode, CameraParameters::SCENE_MODE_SUNSET) ?
2714             ANDROID_CONTROL_SCENE_MODE_SUNSET :
2715         !strcmp(sceneMode, CameraParameters::SCENE_MODE_STEADYPHOTO) ?
2716             ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO :
2717         !strcmp(sceneMode, CameraParameters::SCENE_MODE_FIREWORKS) ?
2718             ANDROID_CONTROL_SCENE_MODE_FIREWORKS :
2719         !strcmp(sceneMode, CameraParameters::SCENE_MODE_SPORTS) ?
2720             ANDROID_CONTROL_SCENE_MODE_SPORTS :
2721         !strcmp(sceneMode, CameraParameters::SCENE_MODE_PARTY) ?
2722             ANDROID_CONTROL_SCENE_MODE_PARTY :
2723         !strcmp(sceneMode, CameraParameters::SCENE_MODE_CANDLELIGHT) ?
2724             ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT :
2725         !strcmp(sceneMode, CameraParameters::SCENE_MODE_BARCODE) ?
2726             ANDROID_CONTROL_SCENE_MODE_BARCODE:
2727         !strcmp(sceneMode, CameraParameters::SCENE_MODE_HDR) ?
2728             ANDROID_CONTROL_SCENE_MODE_HDR:
2729         -1;
2730 }
2731 
flashModeStringToEnum(const char * flashMode)2732 Parameters::Parameters::flashMode_t Parameters::flashModeStringToEnum(
2733         const char *flashMode) {
2734     return
2735         !flashMode ?
2736             Parameters::FLASH_MODE_OFF :
2737         !strcmp(flashMode, CameraParameters::FLASH_MODE_OFF) ?
2738             Parameters::FLASH_MODE_OFF :
2739         !strcmp(flashMode, CameraParameters::FLASH_MODE_AUTO) ?
2740             Parameters::FLASH_MODE_AUTO :
2741         !strcmp(flashMode, CameraParameters::FLASH_MODE_ON) ?
2742             Parameters::FLASH_MODE_ON :
2743         !strcmp(flashMode, CameraParameters::FLASH_MODE_RED_EYE) ?
2744             Parameters::FLASH_MODE_RED_EYE :
2745         !strcmp(flashMode, CameraParameters::FLASH_MODE_TORCH) ?
2746             Parameters::FLASH_MODE_TORCH :
2747         Parameters::FLASH_MODE_INVALID;
2748 }
2749 
flashModeEnumToString(flashMode_t flashMode)2750 const char *Parameters::flashModeEnumToString(flashMode_t flashMode) {
2751     switch (flashMode) {
2752         case FLASH_MODE_OFF:
2753             return CameraParameters::FLASH_MODE_OFF;
2754         case FLASH_MODE_AUTO:
2755             return CameraParameters::FLASH_MODE_AUTO;
2756         case FLASH_MODE_ON:
2757             return CameraParameters::FLASH_MODE_ON;
2758         case FLASH_MODE_RED_EYE:
2759             return CameraParameters::FLASH_MODE_RED_EYE;
2760         case FLASH_MODE_TORCH:
2761             return CameraParameters::FLASH_MODE_TORCH;
2762         default:
2763             ALOGE("%s: Unknown flash mode enum %d",
2764                     __FUNCTION__, flashMode);
2765             return "unknown";
2766     }
2767 }
2768 
focusModeStringToEnum(const char * focusMode)2769 Parameters::Parameters::focusMode_t Parameters::focusModeStringToEnum(
2770         const char *focusMode) {
2771     return
2772         !focusMode ?
2773             Parameters::FOCUS_MODE_INVALID :
2774         !strcmp(focusMode, CameraParameters::FOCUS_MODE_AUTO) ?
2775             Parameters::FOCUS_MODE_AUTO :
2776         !strcmp(focusMode, CameraParameters::FOCUS_MODE_INFINITY) ?
2777             Parameters::FOCUS_MODE_INFINITY :
2778         !strcmp(focusMode, CameraParameters::FOCUS_MODE_MACRO) ?
2779             Parameters::FOCUS_MODE_MACRO :
2780         !strcmp(focusMode, CameraParameters::FOCUS_MODE_FIXED) ?
2781             Parameters::FOCUS_MODE_FIXED :
2782         !strcmp(focusMode, CameraParameters::FOCUS_MODE_EDOF) ?
2783             Parameters::FOCUS_MODE_EDOF :
2784         !strcmp(focusMode, CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO) ?
2785             Parameters::FOCUS_MODE_CONTINUOUS_VIDEO :
2786         !strcmp(focusMode, CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE) ?
2787             Parameters::FOCUS_MODE_CONTINUOUS_PICTURE :
2788         Parameters::FOCUS_MODE_INVALID;
2789 }
2790 
focusModeEnumToString(focusMode_t focusMode)2791 const char *Parameters::focusModeEnumToString(focusMode_t focusMode) {
2792     switch (focusMode) {
2793         case FOCUS_MODE_AUTO:
2794             return CameraParameters::FOCUS_MODE_AUTO;
2795         case FOCUS_MODE_MACRO:
2796             return CameraParameters::FOCUS_MODE_MACRO;
2797         case FOCUS_MODE_CONTINUOUS_VIDEO:
2798             return CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO;
2799         case FOCUS_MODE_CONTINUOUS_PICTURE:
2800             return CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE;
2801         case FOCUS_MODE_EDOF:
2802             return CameraParameters::FOCUS_MODE_EDOF;
2803         case FOCUS_MODE_INFINITY:
2804             return CameraParameters::FOCUS_MODE_INFINITY;
2805         case FOCUS_MODE_FIXED:
2806             return CameraParameters::FOCUS_MODE_FIXED;
2807         default:
2808             ALOGE("%s: Unknown focus mode enum: %d",
2809                     __FUNCTION__, focusMode);
2810             return "unknown";
2811     }
2812 }
2813 
parseAreas(const char * areasCStr,Vector<Parameters::Area> * areas)2814 status_t Parameters::parseAreas(const char *areasCStr,
2815         Vector<Parameters::Area> *areas) {
2816     static const size_t NUM_FIELDS = 5;
2817     areas->clear();
2818     if (areasCStr == NULL) {
2819         // If no key exists, use default (0,0,0,0,0)
2820         areas->push();
2821         return OK;
2822     }
2823     String8 areasStr(areasCStr);
2824     ssize_t areaStart = areasStr.find("(", 0) + 1;
2825     while (areaStart != 0) {
2826         const char* area = areasStr.string() + areaStart;
2827         char *numEnd;
2828         int vals[NUM_FIELDS];
2829         for (size_t i = 0; i < NUM_FIELDS; i++) {
2830             errno = 0;
2831             vals[i] = strtol(area, &numEnd, 10);
2832             if (errno || numEnd == area) return BAD_VALUE;
2833             area = numEnd + 1;
2834         }
2835         areas->push(Parameters::Area(
2836             vals[0], vals[1], vals[2], vals[3], vals[4]) );
2837         areaStart = areasStr.find("(", areaStart) + 1;
2838     }
2839     return OK;
2840 }
2841 
validateAreas(const Vector<Parameters::Area> & areas,size_t maxRegions,AreaKind areaKind) const2842 status_t Parameters::validateAreas(const Vector<Parameters::Area> &areas,
2843                                       size_t maxRegions,
2844                                       AreaKind areaKind) const {
2845     // Definition of valid area can be found in
2846     // include/camera/CameraParameters.h
2847     if (areas.size() == 0) return BAD_VALUE;
2848     if (areas.size() == 1) {
2849         if (areas[0].left == 0 &&
2850                 areas[0].top == 0 &&
2851                 areas[0].right == 0 &&
2852                 areas[0].bottom == 0 &&
2853                 areas[0].weight == 0) {
2854             // Single (0,0,0,0,0) entry is always valid (== driver decides)
2855             return OK;
2856         }
2857     }
2858 
2859     // fixed focus can only set (0,0,0,0,0) focus area
2860     if (areaKind == AREA_KIND_FOCUS && focusMode == FOCUS_MODE_FIXED) {
2861         return BAD_VALUE;
2862     }
2863 
2864     if (areas.size() > maxRegions) {
2865         ALOGE("%s: Too many areas requested: %zu",
2866                 __FUNCTION__, areas.size());
2867         return BAD_VALUE;
2868     }
2869 
2870     for (Vector<Parameters::Area>::const_iterator a = areas.begin();
2871          a != areas.end(); a++) {
2872         if (a->weight < 1 || a->weight > 1000) return BAD_VALUE;
2873         if (a->left < -1000 || a->left > 1000) return BAD_VALUE;
2874         if (a->top < -1000 || a->top > 1000) return BAD_VALUE;
2875         if (a->right < -1000 || a->right > 1000) return BAD_VALUE;
2876         if (a->bottom < -1000 || a->bottom > 1000) return BAD_VALUE;
2877         if (a->left >= a->right) return BAD_VALUE;
2878         if (a->top >= a->bottom) return BAD_VALUE;
2879     }
2880     return OK;
2881 }
2882 
boolFromString(const char * boolStr)2883 bool Parameters::boolFromString(const char *boolStr) {
2884     return !boolStr ? false :
2885         !strcmp(boolStr, CameraParameters::TRUE) ? true :
2886         false;
2887 }
2888 
degToTransform(int degrees,bool mirror)2889 int Parameters::degToTransform(int degrees, bool mirror) {
2890     if (!mirror) {
2891         if (degrees == 0) return 0;
2892         else if (degrees == 90) return HAL_TRANSFORM_ROT_90;
2893         else if (degrees == 180) return HAL_TRANSFORM_ROT_180;
2894         else if (degrees == 270) return HAL_TRANSFORM_ROT_270;
2895     } else {  // Do mirror (horizontal flip)
2896         if (degrees == 0) {           // FLIP_H and ROT_0
2897             return HAL_TRANSFORM_FLIP_H;
2898         } else if (degrees == 90) {   // FLIP_H and ROT_90
2899             return HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90;
2900         } else if (degrees == 180) {  // FLIP_H and ROT_180
2901             return HAL_TRANSFORM_FLIP_V;
2902         } else if (degrees == 270) {  // FLIP_H and ROT_270
2903             return HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90;
2904         }
2905     }
2906     ALOGE("%s: Bad input: %d", __FUNCTION__, degrees);
2907     return -1;
2908 }
2909 
cropXToArray(int x) const2910 int Parameters::cropXToArray(int x) const {
2911     ALOG_ASSERT(x >= 0, "Crop-relative X coordinate = '%d' is out of bounds"
2912                          "(lower = 0)", x);
2913 
2914     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2915     ALOG_ASSERT(x < previewCrop.width, "Crop-relative X coordinate = '%d' "
2916                     "is out of bounds (upper = %f)", x, previewCrop.width);
2917 
2918     int ret = x + previewCrop.left;
2919 
2920     ALOG_ASSERT( (ret >= 0 && ret < fastInfo.arrayWidth),
2921         "Calculated pixel array value X = '%d' is out of bounds (upper = %d)",
2922         ret, fastInfo.arrayWidth);
2923     return ret;
2924 }
2925 
cropYToArray(int y) const2926 int Parameters::cropYToArray(int y) const {
2927     ALOG_ASSERT(y >= 0, "Crop-relative Y coordinate = '%d' is out of bounds "
2928         "(lower = 0)", y);
2929 
2930     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2931     ALOG_ASSERT(y < previewCrop.height, "Crop-relative Y coordinate = '%d' is "
2932                 "out of bounds (upper = %f)", y, previewCrop.height);
2933 
2934     int ret = y + previewCrop.top;
2935 
2936     ALOG_ASSERT( (ret >= 0 && ret < fastInfo.arrayHeight),
2937         "Calculated pixel array value Y = '%d' is out of bounds (upper = %d)",
2938         ret, fastInfo.arrayHeight);
2939 
2940     return ret;
2941 
2942 }
2943 
normalizedXToCrop(int x) const2944 int Parameters::normalizedXToCrop(int x) const {
2945     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2946     return (x + 1000) * (previewCrop.width - 1) / 2000;
2947 }
2948 
normalizedYToCrop(int y) const2949 int Parameters::normalizedYToCrop(int y) const {
2950     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2951     return (y + 1000) * (previewCrop.height - 1) / 2000;
2952 }
2953 
normalizedXToArray(int x) const2954 int Parameters::normalizedXToArray(int x) const {
2955 
2956     // Work-around for HAL pre-scaling the coordinates themselves
2957     if (quirks.meteringCropRegion) {
2958         return (x + 1000) * (fastInfo.arrayWidth - 1) / 2000;
2959     }
2960 
2961     return cropXToArray(normalizedXToCrop(x));
2962 }
2963 
normalizedYToArray(int y) const2964 int Parameters::normalizedYToArray(int y) const {
2965     // Work-around for HAL pre-scaling the coordinates themselves
2966     if (quirks.meteringCropRegion) {
2967         return (y + 1000) * (fastInfo.arrayHeight - 1) / 2000;
2968     }
2969 
2970     return cropYToArray(normalizedYToCrop(y));
2971 }
2972 
2973 
calculatePreviewCrop(const CropRegion & scalerCrop) const2974 Parameters::CropRegion Parameters::calculatePreviewCrop(
2975         const CropRegion &scalerCrop) const {
2976     float left, top, width, height;
2977     float previewAspect = static_cast<float>(previewWidth) / previewHeight;
2978     float cropAspect = scalerCrop.width / scalerCrop.height;
2979 
2980     if (previewAspect > cropAspect) {
2981         width = scalerCrop.width;
2982         height = cropAspect * scalerCrop.height / previewAspect;
2983 
2984         left = scalerCrop.left;
2985         top = scalerCrop.top + (scalerCrop.height - height) / 2;
2986     } else {
2987         width = previewAspect * scalerCrop.width / cropAspect;
2988         height = scalerCrop.height;
2989 
2990         left = scalerCrop.left + (scalerCrop.width - width) / 2;
2991         top = scalerCrop.top;
2992     }
2993 
2994     CropRegion previewCrop = {left, top, width, height};
2995 
2996     return previewCrop;
2997 }
2998 
arrayXToNormalizedWithCrop(int x,const CropRegion & scalerCrop) const2999 int Parameters::arrayXToNormalizedWithCrop(int x,
3000         const CropRegion &scalerCrop) const {
3001     // Work-around for HAL pre-scaling the coordinates themselves
3002     if (quirks.meteringCropRegion) {
3003         return x * 2000 / (fastInfo.arrayWidth - 1) - 1000;
3004     } else {
3005         CropRegion previewCrop = calculatePreviewCrop(scalerCrop);
3006         return (x - previewCrop.left) * 2000 / (previewCrop.width - 1) - 1000;
3007     }
3008 }
3009 
arrayYToNormalizedWithCrop(int y,const CropRegion & scalerCrop) const3010 int Parameters::arrayYToNormalizedWithCrop(int y,
3011         const CropRegion &scalerCrop) const {
3012     // Work-around for HAL pre-scaling the coordinates themselves
3013     if (quirks.meteringCropRegion) {
3014         return y * 2000 / (fastInfo.arrayHeight - 1) - 1000;
3015     } else {
3016         CropRegion previewCrop = calculatePreviewCrop(scalerCrop);
3017         return (y - previewCrop.top) * 2000 / (previewCrop.height - 1) - 1000;
3018     }
3019 }
3020 
getFilteredSizes(const Size & lower,const Size & upper,Vector<Size> * sizes)3021 status_t Parameters::getFilteredSizes(const Size &lower, const Size &upper,
3022         Vector<Size> *sizes) {
3023     if (info == NULL) {
3024         ALOGE("%s: Static metadata is not initialized", __FUNCTION__);
3025         return NO_INIT;
3026     }
3027     if (sizes == NULL) {
3028         ALOGE("%s: Input size is null", __FUNCTION__);
3029         return BAD_VALUE;
3030     }
3031     sizes->clear();
3032 
3033     Vector<StreamConfiguration> scs = getStreamConfigurations();
3034     for (size_t i=0; i < scs.size(); i++) {
3035         const StreamConfiguration &sc = scs[i];
3036         if (sc.isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT &&
3037                 sc.format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
3038                 ((sc.width * sc.height) >= (lower.width * lower.height)) &&
3039                 ((sc.width * sc.height) <= (upper.width * upper.height))) {
3040             int64_t minFrameDuration = getMinFrameDurationNs(
3041                     {sc.width, sc.height}, HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
3042             if (minFrameDuration > MAX_PREVIEW_RECORD_DURATION_NS) {
3043                 // Filter slow sizes from preview/record
3044                 continue;
3045             }
3046             sizes->push({sc.width, sc.height});
3047         }
3048     }
3049 
3050     if (sizes->isEmpty()) {
3051         ALOGE("generated preview size list is empty!!");
3052         return BAD_VALUE;
3053     }
3054     return OK;
3055 }
3056 
getMaxSizeForRatio(float ratio,const int32_t * sizeArray,size_t count)3057 Parameters::Size Parameters::getMaxSizeForRatio(
3058         float ratio, const int32_t* sizeArray, size_t count) {
3059     ALOG_ASSERT(sizeArray != NULL, "size array shouldn't be NULL");
3060     ALOG_ASSERT(count >= 2 && count % 2 == 0, "count must be a positive even number");
3061 
3062     Size maxSize = {0, 0};
3063     for (size_t i = 0; i < count; i += 2) {
3064         if (sizeArray[i] > 0 && sizeArray[i+1] > 0) {
3065             float curRatio = static_cast<float>(sizeArray[i]) / sizeArray[i+1];
3066             if (fabs(curRatio - ratio) < ASPECT_RATIO_TOLERANCE && maxSize.width < sizeArray[i]) {
3067                 maxSize.width = sizeArray[i];
3068                 maxSize.height = sizeArray[i+1];
3069             }
3070         }
3071     }
3072 
3073     if (maxSize.width == 0 || maxSize.height == 0) {
3074         maxSize.width = sizeArray[0];
3075         maxSize.height = sizeArray[1];
3076         ALOGW("Unable to find the size to match the given aspect ratio %f."
3077                 "Fall back to %d x %d", ratio, maxSize.width, maxSize.height);
3078     }
3079 
3080     return maxSize;
3081 }
3082 
getMaxSize(const Vector<Parameters::Size> & sizes)3083 Parameters::Size Parameters::getMaxSize(const Vector<Parameters::Size> &sizes) {
3084     Size maxSize = {-1, -1};
3085     for (size_t i = 0; i < sizes.size(); i++) {
3086         if (sizes[i].width > maxSize.width ||
3087                 (sizes[i].width == maxSize.width && sizes[i].height > maxSize.height )) {
3088             maxSize = sizes[i];
3089         }
3090     }
3091     return maxSize;
3092 }
3093 
getStreamConfigurations()3094 Vector<Parameters::StreamConfiguration> Parameters::getStreamConfigurations() {
3095     const int STREAM_CONFIGURATION_SIZE = 4;
3096     const int STREAM_FORMAT_OFFSET = 0;
3097     const int STREAM_WIDTH_OFFSET = 1;
3098     const int STREAM_HEIGHT_OFFSET = 2;
3099     const int STREAM_IS_INPUT_OFFSET = 3;
3100     Vector<StreamConfiguration> scs;
3101 
3102     camera_metadata_ro_entry_t availableStreamConfigs =
3103                 staticInfo(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
3104     for (size_t i = 0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
3105         int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
3106         int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
3107         int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
3108         int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
3109         StreamConfiguration sc = {format, width, height, isInput};
3110         scs.add(sc);
3111     }
3112     return scs;
3113 }
3114 
getJpegStreamMinFrameDurationNs(Parameters::Size size)3115 int64_t Parameters::getJpegStreamMinFrameDurationNs(Parameters::Size size) {
3116     return getMinFrameDurationNs(size, HAL_PIXEL_FORMAT_BLOB);
3117 }
3118 
getZslStreamMinFrameDurationNs(Parameters::Size size)3119 int64_t Parameters::getZslStreamMinFrameDurationNs(Parameters::Size size) {
3120     return getMinFrameDurationNs(size, HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
3121 }
3122 
getMinFrameDurationNs(Parameters::Size size,int fmt)3123 int64_t Parameters::getMinFrameDurationNs(Parameters::Size size, int fmt) {
3124     const int STREAM_DURATION_SIZE = 4;
3125     const int STREAM_FORMAT_OFFSET = 0;
3126     const int STREAM_WIDTH_OFFSET = 1;
3127     const int STREAM_HEIGHT_OFFSET = 2;
3128     const int STREAM_DURATION_OFFSET = 3;
3129     camera_metadata_ro_entry_t availableStreamMinDurations =
3130                 staticInfo(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
3131     for (size_t i = 0; i < availableStreamMinDurations.count; i+= STREAM_DURATION_SIZE) {
3132         int64_t format = availableStreamMinDurations.data.i64[i + STREAM_FORMAT_OFFSET];
3133         int64_t width = availableStreamMinDurations.data.i64[i + STREAM_WIDTH_OFFSET];
3134         int64_t height = availableStreamMinDurations.data.i64[i + STREAM_HEIGHT_OFFSET];
3135         int64_t duration = availableStreamMinDurations.data.i64[i + STREAM_DURATION_OFFSET];
3136         if (format == fmt && width == size.width && height == size.height) {
3137             return duration;
3138         }
3139     }
3140 
3141     return -1;
3142 }
3143 
isFpsSupported(const Vector<Size> & sizes,int format,int32_t fps)3144 bool Parameters::isFpsSupported(const Vector<Size> &sizes, int format, int32_t fps) {
3145     // Get min frame duration for each size and check if the given fps range can be supported.
3146     for (size_t i = 0 ; i < sizes.size(); i++) {
3147         int64_t minFrameDuration = getMinFrameDurationNs(sizes[i], format);
3148         if (minFrameDuration <= 0) {
3149             ALOGE("Min frame duration (%" PRId64") for size (%dx%d) and format 0x%x is wrong!",
3150                 minFrameDuration, sizes[i].width, sizes[i].height, format);
3151             return false;
3152         }
3153         int32_t maxSupportedFps = 1e9 / minFrameDuration;
3154         // Add some margin here for the case where the hal supports 29.xxxfps.
3155         maxSupportedFps += FPS_MARGIN;
3156         if (fps > maxSupportedFps) {
3157             return false;
3158         }
3159     }
3160     return true;
3161 }
3162 
getAvailableOutputFormats()3163 SortedVector<int32_t> Parameters::getAvailableOutputFormats() {
3164     SortedVector<int32_t> outputFormats; // Non-duplicated output formats
3165     Vector<StreamConfiguration> scs = getStreamConfigurations();
3166     for (size_t i = 0; i < scs.size(); i++) {
3167         const StreamConfiguration &sc = scs[i];
3168         if (sc.isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT) {
3169             outputFormats.add(sc.format);
3170         }
3171     }
3172 
3173     return outputFormats;
3174 }
3175 
getAvailableJpegSizes()3176 Vector<Parameters::Size> Parameters::getAvailableJpegSizes() {
3177     Vector<Parameters::Size> jpegSizes;
3178     Vector<StreamConfiguration> scs = getStreamConfigurations();
3179     for (size_t i = 0; i < scs.size(); i++) {
3180         const StreamConfiguration &sc = scs[i];
3181         if (sc.isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT &&
3182                 sc.format == HAL_PIXEL_FORMAT_BLOB) {
3183             Size sz = {sc.width, sc.height};
3184             jpegSizes.add(sz);
3185         }
3186     }
3187 
3188     return jpegSizes;
3189 }
3190 
getPreferredStreamConfigurations(int32_t usecaseId) const3191 Vector<Parameters::StreamConfiguration> Parameters::getPreferredStreamConfigurations(
3192         int32_t usecaseId) const {
3193     const size_t STREAM_CONFIGURATION_SIZE = 5;
3194     const size_t STREAM_WIDTH_OFFSET = 0;
3195     const size_t STREAM_HEIGHT_OFFSET = 1;
3196     const size_t STREAM_FORMAT_OFFSET = 2;
3197     const size_t STREAM_IS_INPUT_OFFSET = 3;
3198     const size_t STREAM_USECASE_BITMAP_OFFSET = 4;
3199     Vector<StreamConfiguration> scs;
3200 
3201     if (fastInfo.supportsPreferredConfigs) {
3202         camera_metadata_ro_entry_t availableStreamConfigs = staticInfo(
3203                 ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS);
3204         for (size_t i = 0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
3205             int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
3206             int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
3207             int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
3208             int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
3209             int32_t supportedUsecases =
3210                     availableStreamConfigs.data.i32[i + STREAM_USECASE_BITMAP_OFFSET];
3211             if (supportedUsecases & (1 << usecaseId)) {
3212                 StreamConfiguration sc = {format, width, height, isInput};
3213                 scs.add(sc);
3214             }
3215         }
3216     }
3217 
3218     return scs;
3219 }
3220 
getPreferredFilteredSizes(int32_t usecaseId,int32_t format) const3221 Vector<Parameters::Size> Parameters::getPreferredFilteredSizes(int32_t usecaseId,
3222         int32_t format) const {
3223     Vector<Parameters::Size> sizes;
3224     Vector<StreamConfiguration> scs = getPreferredStreamConfigurations(usecaseId);
3225     for (const auto &it : scs) {
3226         if (it.format == format) {
3227             sizes.add({it.width, it.height});
3228         }
3229     }
3230 
3231     return sizes;
3232 }
3233 
getPreferredJpegSizes() const3234 Vector<Parameters::Size> Parameters::getPreferredJpegSizes() const {
3235     return getPreferredFilteredSizes(
3236             ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_SNAPSHOT,
3237             HAL_PIXEL_FORMAT_BLOB);
3238 }
3239 
getPreferredPreviewSizes() const3240 Vector<Parameters::Size> Parameters::getPreferredPreviewSizes() const {
3241     return getPreferredFilteredSizes(
3242             ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_PREVIEW,
3243             HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
3244 }
3245 
getPreferredVideoSizes() const3246 Vector<Parameters::Size> Parameters::getPreferredVideoSizes() const {
3247     return getPreferredFilteredSizes(
3248             ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_RECORD,
3249             HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
3250 }
3251 
calculateCropRegion(bool previewOnly) const3252 Parameters::CropRegion Parameters::calculateCropRegion(bool previewOnly) const {
3253 
3254     float zoomLeft, zoomTop, zoomWidth, zoomHeight;
3255 
3256     // Need to convert zoom index into a crop rectangle. The rectangle is
3257     // chosen to maximize its area on the sensor
3258 
3259     camera_metadata_ro_entry_t maxDigitalZoom =
3260             staticInfo(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
3261     // For each zoom step by how many pixels more do we change the zoom
3262     float zoomIncrement = (maxDigitalZoom.data.f[0] - 1) /
3263             (NUM_ZOOM_STEPS-1);
3264     // The desired activeAreaWidth/cropAreaWidth ratio (or height if h>w)
3265     // via interpolating zoom step into a zoom ratio
3266     float zoomRatio = 1 + zoomIncrement * zoom;
3267     ALOG_ASSERT( (zoomRatio >= 1.f && zoomRatio <= maxDigitalZoom.data.f[0]),
3268         "Zoom ratio calculated out of bounds. Expected 1 - %f, actual: %f",
3269         maxDigitalZoom.data.f[0], zoomRatio);
3270 
3271     ALOGV("Zoom maxDigital=%f, increment=%f, ratio=%f, previewWidth=%d, "
3272           "previewHeight=%d, activeWidth=%d, activeHeight=%d",
3273           maxDigitalZoom.data.f[0], zoomIncrement, zoomRatio, previewWidth,
3274           previewHeight, fastInfo.arrayWidth, fastInfo.arrayHeight);
3275 
3276     if (previewOnly) {
3277         // Calculate a tight crop region for the preview stream only
3278         float previewRatio = static_cast<float>(previewWidth) / previewHeight;
3279 
3280         /* Ensure that the width/height never go out of bounds
3281          * by scaling across a diffent dimension if an out-of-bounds
3282          * possibility exists.
3283          *
3284          * e.g. if the previewratio < arrayratio and e.g. zoomratio = 1.0, then by
3285          * calculating the zoomWidth from zoomHeight we'll actually get a
3286          * zoomheight > arrayheight
3287          */
3288         float arrayRatio = 1.f * fastInfo.arrayWidth / fastInfo.arrayHeight;
3289         if (previewRatio >= arrayRatio) {
3290             // Adjust the height based on the width
3291             zoomWidth =  fastInfo.arrayWidth / zoomRatio;
3292             zoomHeight = zoomWidth *
3293                     previewHeight / previewWidth;
3294 
3295         } else {
3296             // Adjust the width based on the height
3297             zoomHeight = fastInfo.arrayHeight / zoomRatio;
3298             zoomWidth = zoomHeight *
3299                     previewWidth / previewHeight;
3300         }
3301     } else {
3302         // Calculate the global crop region with a shape matching the active
3303         // array.
3304         zoomWidth = fastInfo.arrayWidth / zoomRatio;
3305         zoomHeight = fastInfo.arrayHeight / zoomRatio;
3306     }
3307 
3308     // center the zoom area within the active area
3309     zoomLeft = (fastInfo.arrayWidth - zoomWidth) / 2;
3310     zoomTop = (fastInfo.arrayHeight - zoomHeight) / 2;
3311 
3312     ALOGV("Crop region calculated (x=%d,y=%d,w=%f,h=%f) for zoom=%d",
3313         (int32_t)zoomLeft, (int32_t)zoomTop, zoomWidth, zoomHeight, this->zoom);
3314 
3315     CropRegion crop = { zoomLeft, zoomTop, zoomWidth, zoomHeight };
3316     return crop;
3317 }
3318 
calculatePictureFovs(float * horizFov,float * vertFov) const3319 status_t Parameters::calculatePictureFovs(float *horizFov, float *vertFov)
3320         const {
3321     // For external camera, use FOVs = (-1.0, -1.0) as default values. Calculate
3322     // FOVs only if there is sufficient information.
3323     if (fastInfo.isExternalCamera) {
3324         if (horizFov != NULL) {
3325             *horizFov = -1.0;
3326         }
3327         if (vertFov != NULL) {
3328             *vertFov = -1.0;
3329         }
3330     }
3331 
3332     camera_metadata_ro_entry_t sensorSize =
3333             staticInfo(ANDROID_SENSOR_INFO_PHYSICAL_SIZE, 2, 2);
3334     if (!sensorSize.count) {
3335         // It is non-fatal for external cameras since it has default values.
3336         if (fastInfo.isExternalCamera) {
3337             return OK;
3338         } else {
3339             return NO_INIT;
3340         }
3341     }
3342 
3343     camera_metadata_ro_entry_t pixelArraySize =
3344             staticInfo(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE, 2, 2);
3345     if (!pixelArraySize.count) {
3346         // It is non-fatal for external cameras since it has default values.
3347         if (fastInfo.isExternalCamera) {
3348             return OK;
3349         } else {
3350             return NO_INIT;
3351         }
3352     }
3353 
3354     float arrayAspect = static_cast<float>(fastInfo.arrayWidth) /
3355             fastInfo.arrayHeight;
3356     float stillAspect = static_cast<float>(pictureWidth) / pictureHeight;
3357     ALOGV("Array aspect: %f, still aspect: %f", arrayAspect, stillAspect);
3358 
3359     // The crop factors from the full sensor array to the still picture crop
3360     // region
3361     float horizCropFactor = 1.f;
3362     float vertCropFactor = 1.f;
3363 
3364     /**
3365      * Need to calculate the still image field of view based on the total pixel
3366      * array field of view, and the relative aspect ratios of the pixel array
3367      * and output streams.
3368      *
3369      * Special treatment for quirky definition of crop region and relative
3370      * stream cropping.
3371      */
3372     if (quirks.meteringCropRegion) {
3373         // Use max of preview and video as first crop
3374         float previewAspect = static_cast<float>(previewWidth) / previewHeight;
3375         float videoAspect = static_cast<float>(videoWidth) / videoHeight;
3376         if (videoAspect > previewAspect) {
3377             previewAspect = videoAspect;
3378         }
3379         // First crop sensor to preview aspect ratio
3380         if (arrayAspect < previewAspect) {
3381             vertCropFactor = arrayAspect / previewAspect;
3382         } else {
3383             horizCropFactor = previewAspect / arrayAspect;
3384         }
3385         // Second crop to still aspect ratio
3386         if (stillAspect < previewAspect) {
3387             horizCropFactor *= stillAspect / previewAspect;
3388         } else {
3389             vertCropFactor *= previewAspect / stillAspect;
3390         }
3391     } else {
3392         /**
3393          * Crop are just a function of just the still/array relative aspect
3394          * ratios. Since each stream will maximize its area within the crop
3395          * region, and for FOV we assume a full-sensor crop region, we only ever
3396          * crop the FOV either vertically or horizontally, never both.
3397          */
3398         horizCropFactor = (arrayAspect > stillAspect) ?
3399                 (stillAspect / arrayAspect) : 1.f;
3400         vertCropFactor = (arrayAspect < stillAspect) ?
3401                 (arrayAspect / stillAspect) : 1.f;
3402     }
3403 
3404     /**
3405      * Convert the crop factors w.r.t the active array size to the crop factors
3406      * w.r.t the pixel array size.
3407      */
3408     horizCropFactor *= (static_cast<float>(fastInfo.arrayWidth) /
3409                             pixelArraySize.data.i32[0]);
3410     vertCropFactor *= (static_cast<float>(fastInfo.arrayHeight) /
3411                             pixelArraySize.data.i32[1]);
3412 
3413     ALOGV("Horiz crop factor: %f, vert crop fact: %f",
3414             horizCropFactor, vertCropFactor);
3415     /**
3416      * Basic field of view formula is:
3417      *   angle of view = 2 * arctangent ( d / 2f )
3418      * where d is the physical sensor dimension of interest, and f is
3419      * the focal length. This only applies to rectilinear sensors, for focusing
3420      * at distances >> f, etc.
3421      */
3422     if (horizFov != NULL) {
3423         *horizFov = 180 / M_PI * 2 *
3424                 atanf(horizCropFactor * sensorSize.data.f[0] /
3425                         (2 * fastInfo.defaultFocalLength));
3426     }
3427     if (vertFov != NULL) {
3428         *vertFov = 180 / M_PI * 2 *
3429                 atanf(vertCropFactor * sensorSize.data.f[1] /
3430                         (2 * fastInfo.defaultFocalLength));
3431     }
3432     return OK;
3433 }
3434 
fpsFromRange(int32_t,int32_t max) const3435 int32_t Parameters::fpsFromRange(int32_t /*min*/, int32_t max) const {
3436     return max;
3437 }
3438 
3439 }; // namespace camera2
3440 }; // namespace android
3441