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