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