• 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     params.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK,
802             CameraParameters::FALSE);
803     params.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK_SUPPORTED,
804             CameraParameters::TRUE);
805 
806     autoWhiteBalanceLock = false;
807     params.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK,
808             CameraParameters::FALSE);
809     params.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED,
810             CameraParameters::TRUE);
811 
812     meteringAreas.add(Parameters::Area(0, 0, 0, 0, 0));
813     params.set(CameraParameters::KEY_MAX_NUM_METERING_AREAS,
814             max3aRegions.data.i32[Parameters::REGION_AE]);
815     params.set(CameraParameters::KEY_METERING_AREAS,
816             "(0,0,0,0,0)");
817 
818     zoom = 0;
819     params.set(CameraParameters::KEY_ZOOM, zoom);
820     params.set(CameraParameters::KEY_MAX_ZOOM, NUM_ZOOM_STEPS - 1);
821 
822     camera_metadata_ro_entry_t maxDigitalZoom =
823         staticInfo(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM, /*minCount*/1, /*maxCount*/1);
824     if (!maxDigitalZoom.count) return NO_INIT;
825 
826     {
827         String8 zoomRatios;
828         float zoom = 1.f;
829         float zoomIncrement = (maxDigitalZoom.data.f[0] - zoom) /
830                 (NUM_ZOOM_STEPS-1);
831         bool addComma = false;
832         for (size_t i=0; i < NUM_ZOOM_STEPS; i++) {
833             if (addComma) zoomRatios += ",";
834             addComma = true;
835             zoomRatios += String8::format("%d", static_cast<int>(zoom * 100));
836             zoom += zoomIncrement;
837         }
838         params.set(CameraParameters::KEY_ZOOM_RATIOS, zoomRatios);
839     }
840 
841     params.set(CameraParameters::KEY_ZOOM_SUPPORTED,
842             CameraParameters::TRUE);
843     params.set(CameraParameters::KEY_SMOOTH_ZOOM_SUPPORTED,
844             CameraParameters::FALSE);
845 
846     params.set(CameraParameters::KEY_FOCUS_DISTANCES,
847             "Infinity,Infinity,Infinity");
848 
849     params.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_HW,
850             fastInfo.maxFaces);
851     params.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_SW,
852             0);
853 
854     params.set(CameraParameters::KEY_VIDEO_FRAME_FORMAT,
855             CameraParameters::PIXEL_FORMAT_ANDROID_OPAQUE);
856 
857     recordingHint = false;
858     params.set(CameraParameters::KEY_RECORDING_HINT,
859             CameraParameters::FALSE);
860 
861     params.set(CameraParameters::KEY_VIDEO_SNAPSHOT_SUPPORTED,
862             CameraParameters::TRUE);
863 
864     videoStabilization = false;
865     params.set(CameraParameters::KEY_VIDEO_STABILIZATION,
866             CameraParameters::FALSE);
867 
868     camera_metadata_ro_entry_t availableVideoStabilizationModes =
869         staticInfo(ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES, 0, 0,
870                 false);
871 
872     if (availableVideoStabilizationModes.count > 1) {
873         params.set(CameraParameters::KEY_VIDEO_STABILIZATION_SUPPORTED,
874                 CameraParameters::TRUE);
875     } else {
876         params.set(CameraParameters::KEY_VIDEO_STABILIZATION_SUPPORTED,
877                 CameraParameters::FALSE);
878     }
879 
880     // Set up initial state for non-Camera.Parameters state variables
881     videoFormat = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
882     videoDataSpace = HAL_DATASPACE_V0_BT709;
883     videoBufferMode = hardware::ICamera::VIDEO_BUFFER_MODE_DATA_CALLBACK_YUV;
884     playShutterSound = true;
885     enableFaceDetect = false;
886 
887     enableFocusMoveMessages = false;
888     afTriggerCounter = 1;
889     afStateCounter = 0;
890     currentAfTriggerId = -1;
891     afInMotion = false;
892 
893     precaptureTriggerCounter = 1;
894 
895     takePictureCounter = 0;
896 
897     previewCallbackFlags = 0;
898     previewCallbackOneShot = false;
899     previewCallbackSurface = false;
900 
901     Size maxJpegSize = getMaxSize(getAvailableJpegSizes());
902     int64_t minFrameDurationNs = getJpegStreamMinFrameDurationNs(maxJpegSize);
903 
904     slowJpegMode = false;
905     if (minFrameDurationNs > kSlowJpegModeThreshold) {
906         slowJpegMode = true;
907         // Slow jpeg devices does not support video snapshot without
908         // slowing down preview.
909         // TODO: support video size video snapshot only?
910         params.set(CameraParameters::KEY_VIDEO_SNAPSHOT_SUPPORTED,
911             CameraParameters::FALSE);
912     }
913 
914     char value[PROPERTY_VALUE_MAX];
915     property_get("camera.disable_zsl_mode", value, "0");
916     if (!strcmp(value,"1") || slowJpegMode) {
917         ALOGI("Camera %d: Disabling ZSL mode", cameraId);
918         allowZslMode = false;
919     } else {
920         allowZslMode = true;
921     }
922 
923     ALOGI("%s: allowZslMode: %d slowJpegMode %d", __FUNCTION__, allowZslMode, slowJpegMode);
924 
925     state = STOPPED;
926 
927     paramsFlattened = params.flatten();
928 
929     return OK;
930 }
931 
get() const932 String8 Parameters::get() const {
933     return paramsFlattened;
934 }
935 
buildFastInfo()936 status_t Parameters::buildFastInfo() {
937 
938     camera_metadata_ro_entry_t activeArraySize =
939         staticInfo(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE, 2, 4);
940     if (!activeArraySize.count) return NO_INIT;
941     int32_t arrayWidth;
942     int32_t arrayHeight;
943     if (activeArraySize.count == 2) {
944         ALOGW("%s: Camera %d: activeArraySize is missing xmin/ymin!",
945                 __FUNCTION__, cameraId);
946         arrayWidth = activeArraySize.data.i32[0];
947         arrayHeight = activeArraySize.data.i32[1];
948     } else if (activeArraySize.count == 4) {
949         arrayWidth = activeArraySize.data.i32[2];
950         arrayHeight = activeArraySize.data.i32[3];
951     } else return NO_INIT;
952 
953     // We'll set the target FPS range for still captures to be as wide
954     // as possible to give the HAL maximum latitude for exposure selection
955     camera_metadata_ro_entry_t availableFpsRanges =
956         staticInfo(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES, 2);
957     if (availableFpsRanges.count < 2 || availableFpsRanges.count % 2 != 0) {
958         return NO_INIT;
959     }
960 
961     // Get supported preview fps ranges.
962     Vector<Size> supportedPreviewSizes;
963     Vector<FpsRange> supportedPreviewFpsRanges;
964     const Size PREVIEW_SIZE_BOUND = { MAX_PREVIEW_WIDTH, MAX_PREVIEW_HEIGHT };
965     status_t res = getFilteredSizes(PREVIEW_SIZE_BOUND, &supportedPreviewSizes);
966     if (res != OK) return res;
967     for (size_t i=0; i < availableFpsRanges.count; i += 2) {
968         if (!isFpsSupported(supportedPreviewSizes,
969                 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, availableFpsRanges.data.i32[i+1])) {
970             continue;
971         }
972         FpsRange fpsRange = {availableFpsRanges.data.i32[i], availableFpsRanges.data.i32[i+1]};
973         supportedPreviewFpsRanges.add(fpsRange);
974     }
975     if (supportedPreviewFpsRanges.size() == 0) {
976         ALOGE("Supported preview fps range is empty");
977         return NO_INIT;
978     }
979 
980     int32_t bestStillCaptureFpsRange[2] = {
981         supportedPreviewFpsRanges[0].low, supportedPreviewFpsRanges[0].high
982     };
983     int32_t curRange =
984             bestStillCaptureFpsRange[1] - bestStillCaptureFpsRange[0];
985     for (size_t i = 1; i < supportedPreviewFpsRanges.size(); i ++) {
986         int32_t nextRange =
987                 supportedPreviewFpsRanges[i].high -
988                 supportedPreviewFpsRanges[i].low;
989         if ( (nextRange > curRange) ||       // Maximize size of FPS range first
990                 (nextRange == curRange &&    // Then minimize low-end FPS
991                  bestStillCaptureFpsRange[0] > supportedPreviewFpsRanges[i].low)) {
992 
993             bestStillCaptureFpsRange[0] = supportedPreviewFpsRanges[i].low;
994             bestStillCaptureFpsRange[1] = supportedPreviewFpsRanges[i].high;
995             curRange = nextRange;
996         }
997     }
998 
999     camera_metadata_ro_entry_t availableFaceDetectModes =
1000         staticInfo(ANDROID_STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES, 0, 0,
1001                 false);
1002 
1003     uint8_t bestFaceDetectMode =
1004         ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
1005     for (size_t i = 0 ; i < availableFaceDetectModes.count; i++) {
1006         switch (availableFaceDetectModes.data.u8[i]) {
1007             case ANDROID_STATISTICS_FACE_DETECT_MODE_OFF:
1008                 break;
1009             case ANDROID_STATISTICS_FACE_DETECT_MODE_SIMPLE:
1010                 if (bestFaceDetectMode !=
1011                         ANDROID_STATISTICS_FACE_DETECT_MODE_FULL) {
1012                     bestFaceDetectMode =
1013                         ANDROID_STATISTICS_FACE_DETECT_MODE_SIMPLE;
1014                 }
1015                 break;
1016             case ANDROID_STATISTICS_FACE_DETECT_MODE_FULL:
1017                 bestFaceDetectMode =
1018                     ANDROID_STATISTICS_FACE_DETECT_MODE_FULL;
1019                 break;
1020             default:
1021                 ALOGE("%s: Camera %d: Unknown face detect mode %d:",
1022                         __FUNCTION__, cameraId,
1023                         availableFaceDetectModes.data.u8[i]);
1024                 return NO_INIT;
1025         }
1026     }
1027 
1028     int32_t maxFaces = 0;
1029     camera_metadata_ro_entry_t maxFacesDetected =
1030         staticInfo(ANDROID_STATISTICS_INFO_MAX_FACE_COUNT, 0, 1, false);
1031     if (maxFacesDetected.count) {
1032         maxFaces = maxFacesDetected.data.i32[0];
1033     }
1034 
1035     camera_metadata_ro_entry_t availableSceneModes =
1036         staticInfo(ANDROID_CONTROL_AVAILABLE_SCENE_MODES, 0, 0, false);
1037     camera_metadata_ro_entry_t sceneModeOverrides =
1038         staticInfo(ANDROID_CONTROL_SCENE_MODE_OVERRIDES, 0, 0, false);
1039     camera_metadata_ro_entry_t minFocusDistance =
1040         staticInfo(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE, 0, 0, false);
1041     bool fixedLens = minFocusDistance.count == 0 ||
1042         minFocusDistance.data.f[0] == 0;
1043 
1044     camera_metadata_ro_entry_t focusDistanceCalibration =
1045             staticInfo(ANDROID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION, 0, 0,
1046                     false);
1047     bool canFocusInfinity = (focusDistanceCalibration.count &&
1048             focusDistanceCalibration.data.u8[0] !=
1049             ANDROID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_UNCALIBRATED);
1050 
1051     camera_metadata_ro_entry_t availableFocalLengths =
1052         staticInfo(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS);
1053     if (!availableFocalLengths.count) return NO_INIT;
1054 
1055     SortedVector<int32_t> availableFormats = getAvailableOutputFormats();
1056     if (!availableFormats.size()) return NO_INIT;
1057 
1058 
1059     if (sceneModeOverrides.count > 0) {
1060         // sceneModeOverrides is defined to have 3 entries for each scene mode,
1061         // which are AE, AWB, and AF override modes the HAL wants for that scene
1062         // mode.
1063         const size_t kModesPerSceneMode = 3;
1064         if (sceneModeOverrides.count !=
1065                 availableSceneModes.count * kModesPerSceneMode) {
1066             ALOGE("%s: Camera %d: Scene mode override list is an "
1067                     "unexpected size: %zu (expected %zu)", __FUNCTION__,
1068                     cameraId, sceneModeOverrides.count,
1069                     availableSceneModes.count * kModesPerSceneMode);
1070             return NO_INIT;
1071         }
1072         for (size_t i = 0; i < availableSceneModes.count; i++) {
1073             DeviceInfo::OverrideModes modes;
1074             uint8_t aeMode =
1075                     sceneModeOverrides.data.u8[i * kModesPerSceneMode + 0];
1076             switch(aeMode) {
1077                 case ANDROID_CONTROL_AE_MODE_ON:
1078                     modes.flashMode = FLASH_MODE_OFF;
1079                     break;
1080                 case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH:
1081                     modes.flashMode = FLASH_MODE_AUTO;
1082                     break;
1083                 case ANDROID_CONTROL_AE_MODE_ON_ALWAYS_FLASH:
1084                     modes.flashMode = FLASH_MODE_ON;
1085                     break;
1086                 case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE:
1087                     modes.flashMode = FLASH_MODE_RED_EYE;
1088                     break;
1089                 default:
1090                     ALOGE("%s: Unknown override AE mode: %d", __FUNCTION__,
1091                             aeMode);
1092                     modes.flashMode = FLASH_MODE_INVALID;
1093                     break;
1094             }
1095             modes.wbMode =
1096                     sceneModeOverrides.data.u8[i * kModesPerSceneMode + 1];
1097             uint8_t afMode =
1098                     sceneModeOverrides.data.u8[i * kModesPerSceneMode + 2];
1099             switch(afMode) {
1100                 case ANDROID_CONTROL_AF_MODE_OFF:
1101                     if (!fixedLens && !canFocusInfinity) {
1102                         ALOGE("%s: Camera %d: Scene mode override lists asks for"
1103                                 " fixed focus on a device with focuser but not"
1104                                 " calibrated for infinity focus", __FUNCTION__,
1105                                 cameraId);
1106                         return NO_INIT;
1107                     }
1108                     modes.focusMode = fixedLens ?
1109                             FOCUS_MODE_FIXED : FOCUS_MODE_INFINITY;
1110                     break;
1111                 case ANDROID_CONTROL_AF_MODE_AUTO:
1112                 case ANDROID_CONTROL_AF_MODE_MACRO:
1113                 case ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO:
1114                 case ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE:
1115                 case ANDROID_CONTROL_AF_MODE_EDOF:
1116                     modes.focusMode = static_cast<focusMode_t>(afMode);
1117                     break;
1118                 default:
1119                     ALOGE("%s: Unknown override AF mode: %d", __FUNCTION__,
1120                             afMode);
1121                     modes.focusMode = FOCUS_MODE_INVALID;
1122                     break;
1123             }
1124             fastInfo.sceneModeOverrides.add(availableSceneModes.data.u8[i],
1125                     modes);
1126         }
1127     }
1128 
1129     fastInfo.arrayWidth = arrayWidth;
1130     fastInfo.arrayHeight = arrayHeight;
1131     fastInfo.bestStillCaptureFpsRange[0] = bestStillCaptureFpsRange[0];
1132     fastInfo.bestStillCaptureFpsRange[1] = bestStillCaptureFpsRange[1];
1133     fastInfo.bestFaceDetectMode = bestFaceDetectMode;
1134     fastInfo.maxFaces = maxFaces;
1135 
1136     // Find smallest (widest-angle) focal length to use as basis of still
1137     // picture FOV reporting.
1138     fastInfo.minFocalLength = availableFocalLengths.data.f[0];
1139     for (size_t i = 1; i < availableFocalLengths.count; i++) {
1140         if (fastInfo.minFocalLength > availableFocalLengths.data.f[i]) {
1141             fastInfo.minFocalLength = availableFocalLengths.data.f[i];
1142         }
1143     }
1144 
1145     // Check if the HAL supports HAL_PIXEL_FORMAT_YCbCr_420_888
1146     fastInfo.useFlexibleYuv = false;
1147     for (size_t i = 0; i < availableFormats.size(); i++) {
1148         if (availableFormats[i] == HAL_PIXEL_FORMAT_YCbCr_420_888) {
1149             fastInfo.useFlexibleYuv = true;
1150             break;
1151         }
1152     }
1153     ALOGV("Camera %d: Flexible YUV %s supported",
1154             cameraId, fastInfo.useFlexibleYuv ? "is" : "is not");
1155 
1156     fastInfo.maxJpegSize = getMaxSize(getAvailableJpegSizes());
1157 
1158     return OK;
1159 }
1160 
buildQuirks()1161 status_t Parameters::buildQuirks() {
1162     camera_metadata_ro_entry_t entry;
1163     entry = info->find(ANDROID_QUIRKS_TRIGGER_AF_WITH_AUTO);
1164     quirks.triggerAfWithAuto = (entry.count != 0 && entry.data.u8[0] == 1);
1165     ALOGV_IF(quirks.triggerAfWithAuto, "Camera %d: Quirk triggerAfWithAuto enabled",
1166             cameraId);
1167 
1168     entry = info->find(ANDROID_QUIRKS_USE_ZSL_FORMAT);
1169     quirks.useZslFormat = (entry.count != 0 && entry.data.u8[0] == 1);
1170     ALOGV_IF(quirks.useZslFormat, "Camera %d: Quirk useZslFormat enabled",
1171             cameraId);
1172 
1173     entry = info->find(ANDROID_QUIRKS_METERING_CROP_REGION);
1174     quirks.meteringCropRegion = (entry.count != 0 && entry.data.u8[0] == 1);
1175     ALOGV_IF(quirks.meteringCropRegion, "Camera %d: Quirk meteringCropRegion"
1176                 " enabled", cameraId);
1177 
1178     entry = info->find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
1179     quirks.partialResults = (entry.count != 0 && entry.data.u8[0] == 1);
1180     ALOGV_IF(quirks.partialResults, "Camera %d: Quirk usePartialResult"
1181                 " enabled", cameraId);
1182 
1183     return OK;
1184 }
1185 
staticInfo(uint32_t tag,size_t minCount,size_t maxCount,bool required) const1186 camera_metadata_ro_entry_t Parameters::staticInfo(uint32_t tag,
1187         size_t minCount, size_t maxCount, bool required) const {
1188     camera_metadata_ro_entry_t entry = info->find(tag);
1189 
1190     if (CC_UNLIKELY( entry.count == 0 ) && required) {
1191         const char* tagSection = get_camera_metadata_section_name(tag);
1192         if (tagSection == NULL) tagSection = "<unknown>";
1193         const char* tagName = get_camera_metadata_tag_name(tag);
1194         if (tagName == NULL) tagName = "<unknown>";
1195 
1196         ALOGE("Error finding static metadata entry '%s.%s' (%x)",
1197                 tagSection, tagName, tag);
1198     } else if (CC_UNLIKELY(
1199             (minCount != 0 && entry.count < minCount) ||
1200             (maxCount != 0 && entry.count > maxCount) ) ) {
1201         const char* tagSection = get_camera_metadata_section_name(tag);
1202         if (tagSection == NULL) tagSection = "<unknown>";
1203         const char* tagName = get_camera_metadata_tag_name(tag);
1204         if (tagName == NULL) tagName = "<unknown>";
1205         ALOGE("Malformed static metadata entry '%s.%s' (%x):"
1206                 "Expected between %zu and %zu values, but got %zu values",
1207                 tagSection, tagName, tag, minCount, maxCount, entry.count);
1208     }
1209 
1210     return entry;
1211 }
1212 
set(const String8 & paramString)1213 status_t Parameters::set(const String8& paramString) {
1214     status_t res;
1215 
1216     CameraParameters2 newParams(paramString);
1217 
1218     // TODO: Currently ignoring any changes to supposedly read-only parameters
1219     // such as supported preview sizes, etc. Should probably produce an error if
1220     // they're changed.
1221 
1222     /** Extract and verify new parameters */
1223 
1224     size_t i;
1225 
1226     Parameters validatedParams(*this);
1227 
1228     // PREVIEW_SIZE
1229     newParams.getPreviewSize(&validatedParams.previewWidth,
1230             &validatedParams.previewHeight);
1231 
1232     if (validatedParams.previewWidth != previewWidth ||
1233             validatedParams.previewHeight != previewHeight) {
1234         if (state >= PREVIEW) {
1235             ALOGE("%s: Preview size cannot be updated when preview "
1236                     "is active! (Currently %d x %d, requested %d x %d",
1237                     __FUNCTION__,
1238                     previewWidth, previewHeight,
1239                     validatedParams.previewWidth, validatedParams.previewHeight);
1240             return BAD_VALUE;
1241         }
1242         for (i = 0; i < availablePreviewSizes.size(); i++) {
1243             if ((availablePreviewSizes[i].width ==
1244                     validatedParams.previewWidth) &&
1245                 (availablePreviewSizes[i].height ==
1246                     validatedParams.previewHeight)) break;
1247         }
1248         if (i == availablePreviewSizes.size()) {
1249             ALOGE("%s: Requested preview size %d x %d is not supported",
1250                     __FUNCTION__, validatedParams.previewWidth,
1251                     validatedParams.previewHeight);
1252             return BAD_VALUE;
1253         }
1254     }
1255 
1256     // RECORDING_HINT (always supported)
1257     validatedParams.recordingHint = boolFromString(
1258         newParams.get(CameraParameters::KEY_RECORDING_HINT) );
1259     IF_ALOGV() { // Avoid unused variable warning
1260         bool recordingHintChanged =
1261                 validatedParams.recordingHint != recordingHint;
1262         if (recordingHintChanged) {
1263             ALOGV("%s: Recording hint changed to %d",
1264                   __FUNCTION__, validatedParams.recordingHint);
1265         }
1266     }
1267 
1268     // PREVIEW_FPS_RANGE
1269 
1270     /**
1271      * Use the single FPS value if it was set later than the range.
1272      * Otherwise, use the range value.
1273      */
1274     bool fpsUseSingleValue;
1275     {
1276         const char *fpsRange, *fpsSingle;
1277 
1278         fpsRange = newParams.get(CameraParameters::KEY_PREVIEW_FRAME_RATE);
1279         fpsSingle = newParams.get(CameraParameters::KEY_PREVIEW_FPS_RANGE);
1280 
1281         /**
1282          * Pick either the range or the single key if only one was set.
1283          *
1284          * If both are set, pick the one that has greater set order.
1285          */
1286         if (fpsRange == NULL && fpsSingle == NULL) {
1287             ALOGE("%s: FPS was not set. One of %s or %s must be set.",
1288                   __FUNCTION__, CameraParameters::KEY_PREVIEW_FRAME_RATE,
1289                   CameraParameters::KEY_PREVIEW_FPS_RANGE);
1290             return BAD_VALUE;
1291         } else if (fpsRange == NULL) {
1292             fpsUseSingleValue = true;
1293             ALOGV("%s: FPS range not set, using FPS single value",
1294                   __FUNCTION__);
1295         } else if (fpsSingle == NULL) {
1296             fpsUseSingleValue = false;
1297             ALOGV("%s: FPS single not set, using FPS range value",
1298                   __FUNCTION__);
1299         } else {
1300             int fpsKeyOrder;
1301             res = newParams.compareSetOrder(
1302                     CameraParameters::KEY_PREVIEW_FRAME_RATE,
1303                     CameraParameters::KEY_PREVIEW_FPS_RANGE,
1304                     &fpsKeyOrder);
1305             LOG_ALWAYS_FATAL_IF(res != OK, "Impossibly bad FPS keys");
1306 
1307             fpsUseSingleValue = (fpsKeyOrder > 0);
1308 
1309         }
1310 
1311         ALOGV("%s: Preview FPS value is used from '%s'",
1312               __FUNCTION__, fpsUseSingleValue ? "single" : "range");
1313     }
1314     newParams.getPreviewFpsRange(&validatedParams.previewFpsRange[0],
1315             &validatedParams.previewFpsRange[1]);
1316 
1317     validatedParams.previewFpsRange[0] /= kFpsToApiScale;
1318     validatedParams.previewFpsRange[1] /= kFpsToApiScale;
1319 
1320     // Ignore the FPS range if the FPS single has higher precedence
1321     if (!fpsUseSingleValue) {
1322         ALOGV("%s: Preview FPS range (%d, %d)", __FUNCTION__,
1323                 validatedParams.previewFpsRange[0],
1324                 validatedParams.previewFpsRange[1]);
1325 
1326         camera_metadata_ro_entry_t availablePreviewFpsRanges =
1327             staticInfo(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES, 2);
1328         for (i = 0; i < availablePreviewFpsRanges.count; i += 2) {
1329             if ((availablePreviewFpsRanges.data.i32[i] ==
1330                     validatedParams.previewFpsRange[0]) &&
1331                 (availablePreviewFpsRanges.data.i32[i+1] ==
1332                     validatedParams.previewFpsRange[1]) ) {
1333                 break;
1334             }
1335         }
1336         if (i == availablePreviewFpsRanges.count) {
1337             ALOGE("%s: Requested preview FPS range %d - %d is not supported",
1338                 __FUNCTION__, validatedParams.previewFpsRange[0],
1339                     validatedParams.previewFpsRange[1]);
1340             return BAD_VALUE;
1341         }
1342     }
1343 
1344     // PREVIEW_FORMAT
1345     validatedParams.previewFormat =
1346             formatStringToEnum(newParams.getPreviewFormat());
1347     if (validatedParams.previewFormat != previewFormat) {
1348         if (state >= PREVIEW) {
1349             ALOGE("%s: Preview format cannot be updated when preview "
1350                     "is active!", __FUNCTION__);
1351             return BAD_VALUE;
1352         }
1353         SortedVector<int32_t> availableFormats = getAvailableOutputFormats();
1354         // If using flexible YUV, always support NV21/YV12. Otherwise, check
1355         // HAL's list.
1356         if (! (fastInfo.useFlexibleYuv &&
1357                 (validatedParams.previewFormat ==
1358                         HAL_PIXEL_FORMAT_YCrCb_420_SP ||
1359                  validatedParams.previewFormat ==
1360                         HAL_PIXEL_FORMAT_YV12) ) ) {
1361             // Not using flexible YUV format, so check explicitly
1362             for (i = 0; i < availableFormats.size(); i++) {
1363                 if (availableFormats[i] == validatedParams.previewFormat) break;
1364             }
1365             if (i == availableFormats.size()) {
1366                 ALOGE("%s: Requested preview format %s (0x%x) is not supported",
1367                         __FUNCTION__, newParams.getPreviewFormat(),
1368                         validatedParams.previewFormat);
1369                 return BAD_VALUE;
1370             }
1371         }
1372     }
1373 
1374     // PREVIEW_FRAME_RATE Deprecated
1375     // - Use only if the single FPS value was set later than the FPS range
1376     if (fpsUseSingleValue) {
1377         int previewFps = newParams.getPreviewFrameRate();
1378         ALOGV("%s: Preview FPS single value requested: %d",
1379               __FUNCTION__, previewFps);
1380         {
1381             camera_metadata_ro_entry_t availableFrameRates =
1382                 staticInfo(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES);
1383             /**
1384               * If recording hint is set, find the range that encompasses
1385               * previewFps with the largest min index.
1386               *
1387               * If recording hint is not set, find the range with previewFps
1388               * with the smallest min index.
1389               *
1390               * Either way, in case of multiple ranges, break the tie by
1391               * selecting the smaller range.
1392               */
1393 
1394             // all ranges which have previewFps
1395             Vector<Range> candidateRanges;
1396             for (i = 0; i < availableFrameRates.count; i+=2) {
1397                 Range r = {
1398                             availableFrameRates.data.i32[i],
1399                             availableFrameRates.data.i32[i+1]
1400                 };
1401 
1402                 if (r.min <= previewFps && previewFps <= r.max) {
1403                     candidateRanges.push(r);
1404                 }
1405             }
1406             if (candidateRanges.isEmpty()) {
1407                 ALOGE("%s: Requested preview frame rate %d is not supported",
1408                         __FUNCTION__, previewFps);
1409                 return BAD_VALUE;
1410             }
1411             // most applicable range with targetFps
1412             Range bestRange = candidateRanges[0];
1413             for (i = 1; i < candidateRanges.size(); ++i) {
1414                 Range r = candidateRanges[i];
1415 
1416                 // Find by largest minIndex in recording mode
1417                 if (validatedParams.recordingHint) {
1418                     if (r.min > bestRange.min) {
1419                         bestRange = r;
1420                     }
1421                     else if (r.min == bestRange.min && r.max < bestRange.max) {
1422                         bestRange = r;
1423                     }
1424                 }
1425                 // Find by smallest minIndex in preview mode
1426                 else {
1427                     if (r.min < bestRange.min) {
1428                         bestRange = r;
1429                     }
1430                     else if (r.min == bestRange.min && r.max < bestRange.max) {
1431                         bestRange = r;
1432                     }
1433                 }
1434             }
1435 
1436             validatedParams.previewFpsRange[0] =
1437                     bestRange.min;
1438             validatedParams.previewFpsRange[1] =
1439                     bestRange.max;
1440 
1441             ALOGV("%s: New preview FPS range: %d, %d, recordingHint = %d",
1442                 __FUNCTION__,
1443                 validatedParams.previewFpsRange[0],
1444                 validatedParams.previewFpsRange[1],
1445                 validatedParams.recordingHint);
1446         }
1447     }
1448 
1449     /**
1450      * Update Preview FPS and Preview FPS ranges based on
1451      * what we actually set.
1452      *
1453      * This updates the API-visible (Camera.Parameters#getParameters) values of
1454      * the FPS fields, not only the internal versions.
1455      *
1456      * Order matters: The value that was set last takes precedence.
1457      * - If the client does a setParameters(getParameters()) we retain
1458      *   the same order for preview FPS.
1459      */
1460     if (!fpsUseSingleValue) {
1461         // Set fps single, then fps range (range wins)
1462         newParams.setPreviewFrameRate(
1463                 fpsFromRange(/*min*/validatedParams.previewFpsRange[0],
1464                              /*max*/validatedParams.previewFpsRange[1]));
1465         newParams.setPreviewFpsRange(
1466                 validatedParams.previewFpsRange[0] * kFpsToApiScale,
1467                 validatedParams.previewFpsRange[1] * kFpsToApiScale);
1468     } else {
1469         // Set fps range, then fps single (single wins)
1470         newParams.setPreviewFpsRange(
1471                 validatedParams.previewFpsRange[0] * kFpsToApiScale,
1472                 validatedParams.previewFpsRange[1] * kFpsToApiScale);
1473         // Set this to the same value, but with higher priority
1474         newParams.setPreviewFrameRate(
1475                 newParams.getPreviewFrameRate());
1476     }
1477 
1478     // PICTURE_SIZE
1479     newParams.getPictureSize(&validatedParams.pictureWidth,
1480             &validatedParams.pictureHeight);
1481     if (validatedParams.pictureWidth != pictureWidth ||
1482             validatedParams.pictureHeight != pictureHeight) {
1483         Vector<Size> availablePictureSizes = getAvailableJpegSizes();
1484         for (i = 0; i < availablePictureSizes.size(); i++) {
1485             if ((availablePictureSizes[i].width ==
1486                     validatedParams.pictureWidth) &&
1487                 (availablePictureSizes[i].height ==
1488                     validatedParams.pictureHeight)) break;
1489         }
1490         if (i == availablePictureSizes.size()) {
1491             ALOGE("%s: Requested picture size %d x %d is not supported",
1492                     __FUNCTION__, validatedParams.pictureWidth,
1493                     validatedParams.pictureHeight);
1494             return BAD_VALUE;
1495         }
1496     }
1497 
1498     // JPEG_THUMBNAIL_WIDTH/HEIGHT
1499     validatedParams.jpegThumbSize[0] =
1500             newParams.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
1501     validatedParams.jpegThumbSize[1] =
1502             newParams.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
1503     if (validatedParams.jpegThumbSize[0] != jpegThumbSize[0] ||
1504             validatedParams.jpegThumbSize[1] != jpegThumbSize[1]) {
1505         camera_metadata_ro_entry_t availableJpegThumbSizes =
1506             staticInfo(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1507         for (i = 0; i < availableJpegThumbSizes.count; i+=2) {
1508             if ((availableJpegThumbSizes.data.i32[i] ==
1509                     validatedParams.jpegThumbSize[0]) &&
1510                 (availableJpegThumbSizes.data.i32[i+1] ==
1511                     validatedParams.jpegThumbSize[1])) break;
1512         }
1513         if (i == availableJpegThumbSizes.count) {
1514             ALOGE("%s: Requested JPEG thumbnail size %d x %d is not supported",
1515                     __FUNCTION__, validatedParams.jpegThumbSize[0],
1516                     validatedParams.jpegThumbSize[1]);
1517             return BAD_VALUE;
1518         }
1519     }
1520 
1521     // JPEG_THUMBNAIL_QUALITY
1522     int quality = newParams.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY);
1523     // also makes sure quality fits in uint8_t
1524     if (quality < 0 || quality > 100) {
1525         ALOGE("%s: Requested JPEG thumbnail quality %d is not supported",
1526                 __FUNCTION__, quality);
1527         return BAD_VALUE;
1528     }
1529     validatedParams.jpegThumbQuality = quality;
1530 
1531     // JPEG_QUALITY
1532     quality = newParams.getInt(CameraParameters::KEY_JPEG_QUALITY);
1533     // also makes sure quality fits in uint8_t
1534     if (quality < 0 || quality > 100) {
1535         ALOGE("%s: Requested JPEG quality %d is not supported",
1536                 __FUNCTION__, quality);
1537         return BAD_VALUE;
1538     }
1539     validatedParams.jpegQuality = quality;
1540 
1541     // ROTATION
1542     validatedParams.jpegRotation =
1543             newParams.getInt(CameraParameters::KEY_ROTATION);
1544     if (validatedParams.jpegRotation != 0 &&
1545             validatedParams.jpegRotation != 90 &&
1546             validatedParams.jpegRotation != 180 &&
1547             validatedParams.jpegRotation != 270) {
1548         ALOGE("%s: Requested picture rotation angle %d is not supported",
1549                 __FUNCTION__, validatedParams.jpegRotation);
1550         return BAD_VALUE;
1551     }
1552 
1553     // GPS
1554 
1555     const char *gpsLatStr =
1556             newParams.get(CameraParameters::KEY_GPS_LATITUDE);
1557     if (gpsLatStr != NULL) {
1558         const char *gpsLongStr =
1559                 newParams.get(CameraParameters::KEY_GPS_LONGITUDE);
1560         const char *gpsAltitudeStr =
1561                 newParams.get(CameraParameters::KEY_GPS_ALTITUDE);
1562         const char *gpsTimeStr =
1563                 newParams.get(CameraParameters::KEY_GPS_TIMESTAMP);
1564         const char *gpsProcMethodStr =
1565                 newParams.get(CameraParameters::KEY_GPS_PROCESSING_METHOD);
1566         if (gpsLongStr == NULL ||
1567                 gpsAltitudeStr == NULL ||
1568                 gpsTimeStr == NULL ||
1569                 gpsProcMethodStr == NULL) {
1570             ALOGE("%s: Incomplete set of GPS parameters provided",
1571                     __FUNCTION__);
1572             return BAD_VALUE;
1573         }
1574         char *endPtr;
1575         errno = 0;
1576         validatedParams.gpsCoordinates[0] = strtod(gpsLatStr, &endPtr);
1577         if (errno || endPtr == gpsLatStr) {
1578             ALOGE("%s: Malformed GPS latitude: %s", __FUNCTION__, gpsLatStr);
1579             return BAD_VALUE;
1580         }
1581         errno = 0;
1582         validatedParams.gpsCoordinates[1] = strtod(gpsLongStr, &endPtr);
1583         if (errno || endPtr == gpsLongStr) {
1584             ALOGE("%s: Malformed GPS longitude: %s", __FUNCTION__, gpsLongStr);
1585             return BAD_VALUE;
1586         }
1587         errno = 0;
1588         validatedParams.gpsCoordinates[2] = strtod(gpsAltitudeStr, &endPtr);
1589         if (errno || endPtr == gpsAltitudeStr) {
1590             ALOGE("%s: Malformed GPS altitude: %s", __FUNCTION__,
1591                     gpsAltitudeStr);
1592             return BAD_VALUE;
1593         }
1594         errno = 0;
1595         validatedParams.gpsTimestamp = strtoll(gpsTimeStr, &endPtr, 10);
1596         if (errno || endPtr == gpsTimeStr) {
1597             ALOGE("%s: Malformed GPS timestamp: %s", __FUNCTION__, gpsTimeStr);
1598             return BAD_VALUE;
1599         }
1600         validatedParams.gpsProcessingMethod = gpsProcMethodStr;
1601 
1602         validatedParams.gpsEnabled = true;
1603     } else {
1604         validatedParams.gpsEnabled = false;
1605     }
1606 
1607     // EFFECT
1608     validatedParams.effectMode = effectModeStringToEnum(
1609         newParams.get(CameraParameters::KEY_EFFECT) );
1610     if (validatedParams.effectMode != effectMode) {
1611         camera_metadata_ro_entry_t availableEffectModes =
1612             staticInfo(ANDROID_CONTROL_AVAILABLE_EFFECTS);
1613         for (i = 0; i < availableEffectModes.count; i++) {
1614             if (validatedParams.effectMode == availableEffectModes.data.u8[i]) break;
1615         }
1616         if (i == availableEffectModes.count) {
1617             ALOGE("%s: Requested effect mode \"%s\" is not supported",
1618                     __FUNCTION__,
1619                     newParams.get(CameraParameters::KEY_EFFECT) );
1620             return BAD_VALUE;
1621         }
1622     }
1623 
1624     // ANTIBANDING
1625     validatedParams.antibandingMode = abModeStringToEnum(
1626         newParams.get(CameraParameters::KEY_ANTIBANDING) );
1627     if (validatedParams.antibandingMode != antibandingMode) {
1628         camera_metadata_ro_entry_t availableAbModes =
1629             staticInfo(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES);
1630         for (i = 0; i < availableAbModes.count; i++) {
1631             if (validatedParams.antibandingMode == availableAbModes.data.u8[i])
1632                 break;
1633         }
1634         if (i == availableAbModes.count) {
1635             ALOGE("%s: Requested antibanding mode \"%s\" is not supported",
1636                     __FUNCTION__,
1637                     newParams.get(CameraParameters::KEY_ANTIBANDING));
1638             return BAD_VALUE;
1639         }
1640     }
1641 
1642     // SCENE_MODE
1643     validatedParams.sceneMode = sceneModeStringToEnum(
1644         newParams.get(CameraParameters::KEY_SCENE_MODE) );
1645     if (validatedParams.sceneMode != sceneMode &&
1646             validatedParams.sceneMode !=
1647             ANDROID_CONTROL_SCENE_MODE_DISABLED) {
1648         camera_metadata_ro_entry_t availableSceneModes =
1649             staticInfo(ANDROID_CONTROL_AVAILABLE_SCENE_MODES);
1650         for (i = 0; i < availableSceneModes.count; i++) {
1651             if (validatedParams.sceneMode == availableSceneModes.data.u8[i])
1652                 break;
1653         }
1654         if (i == availableSceneModes.count) {
1655             ALOGE("%s: Requested scene mode \"%s\" is not supported",
1656                     __FUNCTION__,
1657                     newParams.get(CameraParameters::KEY_SCENE_MODE));
1658             return BAD_VALUE;
1659         }
1660     }
1661     bool sceneModeSet =
1662             validatedParams.sceneMode != ANDROID_CONTROL_SCENE_MODE_DISABLED;
1663 
1664     // FLASH_MODE
1665     if (sceneModeSet) {
1666         validatedParams.flashMode =
1667                 fastInfo.sceneModeOverrides.
1668                         valueFor(validatedParams.sceneMode).flashMode;
1669     } else {
1670         validatedParams.flashMode = FLASH_MODE_INVALID;
1671     }
1672     if (validatedParams.flashMode == FLASH_MODE_INVALID) {
1673         validatedParams.flashMode = flashModeStringToEnum(
1674             newParams.get(CameraParameters::KEY_FLASH_MODE) );
1675     }
1676 
1677     if (validatedParams.flashMode != flashMode) {
1678         camera_metadata_ro_entry_t flashAvailable =
1679             staticInfo(ANDROID_FLASH_INFO_AVAILABLE, 1, 1);
1680         bool isFlashAvailable =
1681                 flashAvailable.data.u8[0] == ANDROID_FLASH_INFO_AVAILABLE_TRUE;
1682         if (!isFlashAvailable &&
1683                 validatedParams.flashMode != Parameters::FLASH_MODE_OFF) {
1684             ALOGE("%s: Requested flash mode \"%s\" is not supported: "
1685                     "No flash on device", __FUNCTION__,
1686                     newParams.get(CameraParameters::KEY_FLASH_MODE));
1687             return BAD_VALUE;
1688         } else if (validatedParams.flashMode == Parameters::FLASH_MODE_RED_EYE) {
1689             camera_metadata_ro_entry_t availableAeModes =
1690                 staticInfo(ANDROID_CONTROL_AE_AVAILABLE_MODES);
1691             for (i = 0; i < availableAeModes.count; i++) {
1692                 if (validatedParams.flashMode == availableAeModes.data.u8[i])
1693                     break;
1694             }
1695             if (i == availableAeModes.count) {
1696                 ALOGE("%s: Requested flash mode \"%s\" is not supported",
1697                         __FUNCTION__,
1698                         newParams.get(CameraParameters::KEY_FLASH_MODE));
1699                 return BAD_VALUE;
1700             }
1701         } else if (validatedParams.flashMode == -1) {
1702             ALOGE("%s: Requested flash mode \"%s\" is unknown",
1703                     __FUNCTION__,
1704                     newParams.get(CameraParameters::KEY_FLASH_MODE));
1705             return BAD_VALUE;
1706         }
1707         // Update in case of override, but only if flash is supported
1708         if (isFlashAvailable) {
1709             newParams.set(CameraParameters::KEY_FLASH_MODE,
1710                     flashModeEnumToString(validatedParams.flashMode));
1711         }
1712     }
1713 
1714     // WHITE_BALANCE
1715     if (sceneModeSet) {
1716         validatedParams.wbMode =
1717                 fastInfo.sceneModeOverrides.
1718                         valueFor(validatedParams.sceneMode).wbMode;
1719     } else {
1720         validatedParams.wbMode = ANDROID_CONTROL_AWB_MODE_OFF;
1721     }
1722     if (validatedParams.wbMode == ANDROID_CONTROL_AWB_MODE_OFF) {
1723         validatedParams.wbMode = wbModeStringToEnum(
1724             newParams.get(CameraParameters::KEY_WHITE_BALANCE) );
1725     }
1726     if (validatedParams.wbMode != wbMode) {
1727         camera_metadata_ro_entry_t availableWbModes =
1728             staticInfo(ANDROID_CONTROL_AWB_AVAILABLE_MODES, 0, 0, false);
1729         for (i = 0; i < availableWbModes.count; i++) {
1730             if (validatedParams.wbMode == availableWbModes.data.u8[i]) break;
1731         }
1732         if (i == availableWbModes.count) {
1733             ALOGE("%s: Requested white balance mode %s is not supported",
1734                     __FUNCTION__,
1735                     newParams.get(CameraParameters::KEY_WHITE_BALANCE));
1736             return BAD_VALUE;
1737         }
1738         // Update in case of override
1739         newParams.set(CameraParameters::KEY_WHITE_BALANCE,
1740                 wbModeEnumToString(validatedParams.wbMode));
1741     }
1742 
1743     // FOCUS_MODE
1744     if (sceneModeSet) {
1745         validatedParams.focusMode =
1746                 fastInfo.sceneModeOverrides.
1747                         valueFor(validatedParams.sceneMode).focusMode;
1748     } else {
1749         validatedParams.focusMode = FOCUS_MODE_INVALID;
1750     }
1751     if (validatedParams.focusMode == FOCUS_MODE_INVALID) {
1752         validatedParams.focusMode = focusModeStringToEnum(
1753                 newParams.get(CameraParameters::KEY_FOCUS_MODE) );
1754     }
1755     if (validatedParams.focusMode != focusMode) {
1756         validatedParams.currentAfTriggerId = -1;
1757         if (validatedParams.focusMode != Parameters::FOCUS_MODE_FIXED) {
1758             camera_metadata_ro_entry_t minFocusDistance =
1759                 staticInfo(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE, 0, 0,
1760                         false);
1761             if (minFocusDistance.count && minFocusDistance.data.f[0] == 0) {
1762                 ALOGE("%s: Requested focus mode \"%s\" is not available: "
1763                         "fixed focus lens",
1764                         __FUNCTION__,
1765                         newParams.get(CameraParameters::KEY_FOCUS_MODE));
1766                 return BAD_VALUE;
1767             } else if (validatedParams.focusMode !=
1768                     Parameters::FOCUS_MODE_INFINITY) {
1769                 camera_metadata_ro_entry_t availableFocusModes =
1770                     staticInfo(ANDROID_CONTROL_AF_AVAILABLE_MODES);
1771                 for (i = 0; i < availableFocusModes.count; i++) {
1772                     if (validatedParams.focusMode ==
1773                             availableFocusModes.data.u8[i]) break;
1774                 }
1775                 if (i == availableFocusModes.count) {
1776                     ALOGE("%s: Requested focus mode \"%s\" is not supported",
1777                             __FUNCTION__,
1778                             newParams.get(CameraParameters::KEY_FOCUS_MODE));
1779                     return BAD_VALUE;
1780                 }
1781             }
1782         }
1783         validatedParams.focusState = ANDROID_CONTROL_AF_STATE_INACTIVE;
1784         // Always reset shadow focus mode to avoid reverting settings
1785         validatedParams.shadowFocusMode = FOCUS_MODE_INVALID;
1786         // Update in case of override
1787         newParams.set(CameraParameters::KEY_FOCUS_MODE,
1788                 focusModeEnumToString(validatedParams.focusMode));
1789     } else {
1790         validatedParams.currentAfTriggerId = currentAfTriggerId;
1791     }
1792 
1793     // FOCUS_AREAS
1794     res = parseAreas(newParams.get(CameraParameters::KEY_FOCUS_AREAS),
1795             &validatedParams.focusingAreas);
1796     size_t maxAfRegions = (size_t)staticInfo(ANDROID_CONTROL_MAX_REGIONS,
1797               Parameters::NUM_REGION, Parameters::NUM_REGION).
1798               data.i32[Parameters::REGION_AF];
1799     if (res == OK) res = validateAreas(validatedParams.focusingAreas,
1800             maxAfRegions, AREA_KIND_FOCUS);
1801     if (res != OK) {
1802         ALOGE("%s: Requested focus areas are malformed: %s",
1803                 __FUNCTION__, newParams.get(CameraParameters::KEY_FOCUS_AREAS));
1804         return BAD_VALUE;
1805     }
1806 
1807     // EXPOSURE_COMPENSATION
1808     validatedParams.exposureCompensation =
1809         newParams.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION);
1810     camera_metadata_ro_entry_t exposureCompensationRange =
1811         staticInfo(ANDROID_CONTROL_AE_COMPENSATION_RANGE);
1812     if ((validatedParams.exposureCompensation <
1813             exposureCompensationRange.data.i32[0]) ||
1814         (validatedParams.exposureCompensation >
1815             exposureCompensationRange.data.i32[1])) {
1816         ALOGE("%s: Requested exposure compensation index is out of bounds: %d",
1817                 __FUNCTION__, validatedParams.exposureCompensation);
1818         return BAD_VALUE;
1819     }
1820 
1821     // AUTO_EXPOSURE_LOCK (always supported)
1822     validatedParams.autoExposureLock = boolFromString(
1823         newParams.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK));
1824 
1825     // AUTO_WHITEBALANCE_LOCK (always supported)
1826     validatedParams.autoWhiteBalanceLock = boolFromString(
1827         newParams.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK));
1828 
1829     // METERING_AREAS
1830     size_t maxAeRegions = (size_t)staticInfo(ANDROID_CONTROL_MAX_REGIONS,
1831             Parameters::NUM_REGION, Parameters::NUM_REGION).
1832             data.i32[Parameters::REGION_AE];
1833     res = parseAreas(newParams.get(CameraParameters::KEY_METERING_AREAS),
1834             &validatedParams.meteringAreas);
1835     if (res == OK) {
1836         res = validateAreas(validatedParams.meteringAreas, maxAeRegions,
1837                             AREA_KIND_METERING);
1838     }
1839     if (res != OK) {
1840         ALOGE("%s: Requested metering areas are malformed: %s",
1841                 __FUNCTION__,
1842                 newParams.get(CameraParameters::KEY_METERING_AREAS));
1843         return BAD_VALUE;
1844     }
1845 
1846     // ZOOM
1847     validatedParams.zoom = newParams.getInt(CameraParameters::KEY_ZOOM);
1848     if (validatedParams.zoom < 0
1849                 || validatedParams.zoom >= (int)NUM_ZOOM_STEPS) {
1850         ALOGE("%s: Requested zoom level %d is not supported",
1851                 __FUNCTION__, validatedParams.zoom);
1852         return BAD_VALUE;
1853     }
1854 
1855     // VIDEO_SIZE
1856     newParams.getVideoSize(&validatedParams.videoWidth,
1857             &validatedParams.videoHeight);
1858     if (validatedParams.videoWidth != videoWidth ||
1859             validatedParams.videoHeight != videoHeight) {
1860         if (state == RECORD) {
1861             ALOGW("%s: Video size cannot be updated (from %d x %d to %d x %d)"
1862                     " when recording is active! Ignore the size update!",
1863                     __FUNCTION__, videoWidth, videoHeight, validatedParams.videoWidth,
1864                     validatedParams.videoHeight);
1865             validatedParams.videoWidth = videoWidth;
1866             validatedParams.videoHeight = videoHeight;
1867             newParams.setVideoSize(videoWidth, videoHeight);
1868         } else {
1869             for (i = 0; i < availableVideoSizes.size(); i++) {
1870                 if ((availableVideoSizes[i].width ==
1871                         validatedParams.videoWidth) &&
1872                     (availableVideoSizes[i].height ==
1873                         validatedParams.videoHeight)) break;
1874             }
1875             if (i == availableVideoSizes.size()) {
1876                 ALOGE("%s: Requested video size %d x %d is not supported",
1877                         __FUNCTION__, validatedParams.videoWidth,
1878                         validatedParams.videoHeight);
1879                 return BAD_VALUE;
1880             }
1881         }
1882     }
1883 
1884     // VIDEO_STABILIZATION
1885     validatedParams.videoStabilization = boolFromString(
1886         newParams.get(CameraParameters::KEY_VIDEO_STABILIZATION) );
1887     camera_metadata_ro_entry_t availableVideoStabilizationModes =
1888         staticInfo(ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES, 0, 0,
1889                 false);
1890     if (validatedParams.videoStabilization &&
1891             availableVideoStabilizationModes.count == 1) {
1892         ALOGE("%s: Video stabilization not supported", __FUNCTION__);
1893     }
1894 
1895     /** Update internal parameters */
1896 
1897     *this = validatedParams;
1898     updateOverriddenJpegSize();
1899 
1900     /** Update external parameters calculated from the internal ones */
1901 
1902     // HORIZONTAL/VERTICAL FIELD OF VIEW
1903     float horizFov, vertFov;
1904     res = calculatePictureFovs(&horizFov, &vertFov);
1905     if (res != OK) {
1906         ALOGE("%s: Can't calculate FOVs", __FUNCTION__);
1907         // continue so parameters are at least consistent
1908     }
1909     newParams.setFloat(CameraParameters::KEY_HORIZONTAL_VIEW_ANGLE,
1910             horizFov);
1911     newParams.setFloat(CameraParameters::KEY_VERTICAL_VIEW_ANGLE,
1912             vertFov);
1913     ALOGV("Current still picture FOV: %f x %f deg", horizFov, vertFov);
1914 
1915     // Need to flatten again in case of overrides
1916     paramsFlattened = newParams.flatten();
1917     params = newParams;
1918 
1919     return OK;
1920 }
1921 
updateRequest(CameraMetadata * request) const1922 status_t Parameters::updateRequest(CameraMetadata *request) const {
1923     ATRACE_CALL();
1924     status_t res;
1925 
1926     /**
1927      * Mixin default important security values
1928      * - android.led.transmit = defaulted ON
1929      */
1930     camera_metadata_ro_entry_t entry = staticInfo(ANDROID_LED_AVAILABLE_LEDS,
1931                                                   /*minimumCount*/0,
1932                                                   /*maximumCount*/0,
1933                                                   /*required*/false);
1934     for(size_t i = 0; i < entry.count; ++i) {
1935         uint8_t led = entry.data.u8[i];
1936 
1937         switch(led) {
1938             // Transmit LED is unconditionally on when using
1939             // the android.hardware.Camera API
1940             case ANDROID_LED_AVAILABLE_LEDS_TRANSMIT: {
1941                 uint8_t transmitDefault = ANDROID_LED_TRANSMIT_ON;
1942                 res = request->update(ANDROID_LED_TRANSMIT,
1943                                       &transmitDefault, 1);
1944                 if (res != OK) return res;
1945                 break;
1946             }
1947         }
1948     }
1949 
1950     /**
1951      * Construct metadata from parameters
1952      */
1953 
1954     uint8_t metadataMode = ANDROID_REQUEST_METADATA_MODE_FULL;
1955     res = request->update(ANDROID_REQUEST_METADATA_MODE,
1956             &metadataMode, 1);
1957     if (res != OK) return res;
1958 
1959     camera_metadata_entry_t intent =
1960             request->find(ANDROID_CONTROL_CAPTURE_INTENT);
1961 
1962     if (intent.count == 0) return BAD_VALUE;
1963 
1964     if (intent.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE) {
1965         res = request->update(ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
1966                 fastInfo.bestStillCaptureFpsRange, 2);
1967     } else {
1968         res = request->update(ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
1969                 previewFpsRange, 2);
1970     }
1971     if (res != OK) return res;
1972 
1973     uint8_t reqWbLock = autoWhiteBalanceLock ?
1974             ANDROID_CONTROL_AWB_LOCK_ON : ANDROID_CONTROL_AWB_LOCK_OFF;
1975     res = request->update(ANDROID_CONTROL_AWB_LOCK,
1976             &reqWbLock, 1);
1977 
1978     res = request->update(ANDROID_CONTROL_EFFECT_MODE,
1979             &effectMode, 1);
1980     if (res != OK) return res;
1981     res = request->update(ANDROID_CONTROL_AE_ANTIBANDING_MODE,
1982             &antibandingMode, 1);
1983     if (res != OK) return res;
1984 
1985     // android.hardware.Camera requires that when face detect is enabled, the
1986     // camera is in a face-priority mode. HAL3.x splits this into separate parts
1987     // (face detection statistics and face priority scene mode). Map from other
1988     // to the other.
1989     bool sceneModeActive =
1990             sceneMode != (uint8_t)ANDROID_CONTROL_SCENE_MODE_DISABLED;
1991     uint8_t reqControlMode = ANDROID_CONTROL_MODE_AUTO;
1992     if (enableFaceDetect || sceneModeActive) {
1993         reqControlMode = ANDROID_CONTROL_MODE_USE_SCENE_MODE;
1994     }
1995     res = request->update(ANDROID_CONTROL_MODE,
1996             &reqControlMode, 1);
1997     if (res != OK) return res;
1998 
1999     uint8_t reqSceneMode =
2000             sceneModeActive ? sceneMode :
2001             enableFaceDetect ? (uint8_t)ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY :
2002             (uint8_t)ANDROID_CONTROL_SCENE_MODE_DISABLED;
2003     res = request->update(ANDROID_CONTROL_SCENE_MODE,
2004             &reqSceneMode, 1);
2005     if (res != OK) return res;
2006 
2007     uint8_t reqFlashMode = ANDROID_FLASH_MODE_OFF;
2008     uint8_t reqAeMode = ANDROID_CONTROL_AE_MODE_OFF;
2009     switch (flashMode) {
2010         case Parameters::FLASH_MODE_OFF:
2011             reqAeMode = ANDROID_CONTROL_AE_MODE_ON; break;
2012         case Parameters::FLASH_MODE_AUTO:
2013             reqAeMode = ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH; break;
2014         case Parameters::FLASH_MODE_ON:
2015             reqAeMode = ANDROID_CONTROL_AE_MODE_ON_ALWAYS_FLASH; break;
2016         case Parameters::FLASH_MODE_TORCH:
2017             reqAeMode = ANDROID_CONTROL_AE_MODE_ON;
2018             reqFlashMode = ANDROID_FLASH_MODE_TORCH;
2019             break;
2020         case Parameters::FLASH_MODE_RED_EYE:
2021             reqAeMode = ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE; break;
2022         default:
2023             ALOGE("%s: Camera %d: Unknown flash mode %d", __FUNCTION__,
2024                     cameraId, flashMode);
2025                 return BAD_VALUE;
2026     }
2027     res = request->update(ANDROID_FLASH_MODE,
2028             &reqFlashMode, 1);
2029     if (res != OK) return res;
2030     res = request->update(ANDROID_CONTROL_AE_MODE,
2031             &reqAeMode, 1);
2032     if (res != OK) return res;
2033 
2034     uint8_t reqAeLock = autoExposureLock ?
2035             ANDROID_CONTROL_AE_LOCK_ON : ANDROID_CONTROL_AE_LOCK_OFF;
2036     res = request->update(ANDROID_CONTROL_AE_LOCK,
2037             &reqAeLock, 1);
2038     if (res != OK) return res;
2039 
2040     res = request->update(ANDROID_CONTROL_AWB_MODE,
2041             &wbMode, 1);
2042     if (res != OK) return res;
2043 
2044     float reqFocusDistance = 0; // infinity focus in diopters
2045     uint8_t reqFocusMode = ANDROID_CONTROL_AF_MODE_OFF;
2046     switch (focusMode) {
2047         case Parameters::FOCUS_MODE_AUTO:
2048         case Parameters::FOCUS_MODE_MACRO:
2049         case Parameters::FOCUS_MODE_CONTINUOUS_VIDEO:
2050         case Parameters::FOCUS_MODE_CONTINUOUS_PICTURE:
2051         case Parameters::FOCUS_MODE_EDOF:
2052             reqFocusMode = focusMode;
2053             break;
2054         case Parameters::FOCUS_MODE_INFINITY:
2055         case Parameters::FOCUS_MODE_FIXED:
2056             reqFocusMode = ANDROID_CONTROL_AF_MODE_OFF;
2057             break;
2058         default:
2059                 ALOGE("%s: Camera %d: Unknown focus mode %d", __FUNCTION__,
2060                         cameraId, focusMode);
2061                 return BAD_VALUE;
2062     }
2063     res = request->update(ANDROID_LENS_FOCUS_DISTANCE,
2064             &reqFocusDistance, 1);
2065     if (res != OK) return res;
2066     res = request->update(ANDROID_CONTROL_AF_MODE,
2067             &reqFocusMode, 1);
2068     if (res != OK) return res;
2069 
2070     size_t reqFocusingAreasSize = focusingAreas.size() * 5;
2071     int32_t *reqFocusingAreas = new int32_t[reqFocusingAreasSize];
2072     for (size_t i = 0, j = 0; i < reqFocusingAreasSize; i += 5, j++) {
2073         if (focusingAreas[j].weight != 0) {
2074             reqFocusingAreas[i + 0] =
2075                     normalizedXToArray(focusingAreas[j].left);
2076             reqFocusingAreas[i + 1] =
2077                     normalizedYToArray(focusingAreas[j].top);
2078             reqFocusingAreas[i + 2] =
2079                     normalizedXToArray(focusingAreas[j].right);
2080             reqFocusingAreas[i + 3] =
2081                     normalizedYToArray(focusingAreas[j].bottom);
2082         } else {
2083             reqFocusingAreas[i + 0] = 0;
2084             reqFocusingAreas[i + 1] = 0;
2085             reqFocusingAreas[i + 2] = 0;
2086             reqFocusingAreas[i + 3] = 0;
2087         }
2088         reqFocusingAreas[i + 4] = focusingAreas[j].weight;
2089     }
2090     res = request->update(ANDROID_CONTROL_AF_REGIONS,
2091             reqFocusingAreas, reqFocusingAreasSize);
2092     if (res != OK) return res;
2093     delete[] reqFocusingAreas;
2094 
2095     res = request->update(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION,
2096             &exposureCompensation, 1);
2097     if (res != OK) return res;
2098 
2099     size_t reqMeteringAreasSize = meteringAreas.size() * 5;
2100     int32_t *reqMeteringAreas = new int32_t[reqMeteringAreasSize];
2101     for (size_t i = 0, j = 0; i < reqMeteringAreasSize; i += 5, j++) {
2102         if (meteringAreas[j].weight != 0) {
2103             reqMeteringAreas[i + 0] =
2104                 normalizedXToArray(meteringAreas[j].left);
2105             reqMeteringAreas[i + 1] =
2106                 normalizedYToArray(meteringAreas[j].top);
2107             reqMeteringAreas[i + 2] =
2108                 normalizedXToArray(meteringAreas[j].right);
2109             reqMeteringAreas[i + 3] =
2110                 normalizedYToArray(meteringAreas[j].bottom);
2111         } else {
2112             reqMeteringAreas[i + 0] = 0;
2113             reqMeteringAreas[i + 1] = 0;
2114             reqMeteringAreas[i + 2] = 0;
2115             reqMeteringAreas[i + 3] = 0;
2116         }
2117         reqMeteringAreas[i + 4] = meteringAreas[j].weight;
2118     }
2119     res = request->update(ANDROID_CONTROL_AE_REGIONS,
2120             reqMeteringAreas, reqMeteringAreasSize);
2121     if (res != OK) return res;
2122 
2123     // Set awb regions to be the same as the metering regions if allowed
2124     size_t maxAwbRegions = (size_t)staticInfo(ANDROID_CONTROL_MAX_REGIONS,
2125             Parameters::NUM_REGION, Parameters::NUM_REGION).
2126             data.i32[Parameters::REGION_AWB];
2127     if (maxAwbRegions > 0) {
2128         if (maxAwbRegions >= meteringAreas.size()) {
2129             res = request->update(ANDROID_CONTROL_AWB_REGIONS,
2130                     reqMeteringAreas, reqMeteringAreasSize);
2131         } else {
2132             // Ensure the awb regions are zeroed if the region count is too high.
2133             int32_t zeroedAwbAreas[5] = {0, 0, 0, 0, 0};
2134             res = request->update(ANDROID_CONTROL_AWB_REGIONS,
2135                     zeroedAwbAreas, sizeof(zeroedAwbAreas)/sizeof(int32_t));
2136         }
2137         if (res != OK) return res;
2138     }
2139 
2140     delete[] reqMeteringAreas;
2141 
2142     CropRegion crop = calculateCropRegion(/*previewOnly*/ false);
2143     int32_t reqCropRegion[4] = {
2144         static_cast<int32_t>(crop.left),
2145         static_cast<int32_t>(crop.top),
2146         static_cast<int32_t>(crop.width),
2147         static_cast<int32_t>(crop.height)
2148     };
2149     res = request->update(ANDROID_SCALER_CROP_REGION,
2150             reqCropRegion, 4);
2151     if (res != OK) return res;
2152 
2153     uint8_t reqVstabMode = videoStabilization ?
2154             ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_ON :
2155             ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2156     res = request->update(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
2157             &reqVstabMode, 1);
2158     if (res != OK) return res;
2159 
2160     uint8_t reqFaceDetectMode = enableFaceDetect ?
2161             fastInfo.bestFaceDetectMode :
2162             (uint8_t)ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2163     res = request->update(ANDROID_STATISTICS_FACE_DETECT_MODE,
2164             &reqFaceDetectMode, 1);
2165     if (res != OK) return res;
2166 
2167     return OK;
2168 }
2169 
updateRequestJpeg(CameraMetadata * request) const2170 status_t Parameters::updateRequestJpeg(CameraMetadata *request) const {
2171     status_t res;
2172 
2173     res = request->update(ANDROID_JPEG_THUMBNAIL_SIZE,
2174             jpegThumbSize, 2);
2175     if (res != OK) return res;
2176     res = request->update(ANDROID_JPEG_THUMBNAIL_QUALITY,
2177             &jpegThumbQuality, 1);
2178     if (res != OK) return res;
2179     res = request->update(ANDROID_JPEG_QUALITY,
2180             &jpegQuality, 1);
2181     if (res != OK) return res;
2182     res = request->update(
2183             ANDROID_JPEG_ORIENTATION,
2184             &jpegRotation, 1);
2185     if (res != OK) return res;
2186 
2187     if (gpsEnabled) {
2188         res = request->update(
2189                 ANDROID_JPEG_GPS_COORDINATES,
2190                 gpsCoordinates, 3);
2191         if (res != OK) return res;
2192         res = request->update(
2193                 ANDROID_JPEG_GPS_TIMESTAMP,
2194                 &gpsTimestamp, 1);
2195         if (res != OK) return res;
2196         res = request->update(
2197                 ANDROID_JPEG_GPS_PROCESSING_METHOD,
2198                 gpsProcessingMethod);
2199         if (res != OK) return res;
2200     } else {
2201         res = request->erase(ANDROID_JPEG_GPS_COORDINATES);
2202         if (res != OK) return res;
2203         res = request->erase(ANDROID_JPEG_GPS_TIMESTAMP);
2204         if (res != OK) return res;
2205         res = request->erase(ANDROID_JPEG_GPS_PROCESSING_METHOD);
2206         if (res != OK) return res;
2207     }
2208     return OK;
2209 }
2210 
overrideJpegSizeByVideoSize()2211 status_t Parameters::overrideJpegSizeByVideoSize() {
2212     if (pictureSizeOverriden) {
2213         ALOGV("Picture size has been overridden. Skip overriding");
2214         return OK;
2215     }
2216 
2217     pictureSizeOverriden = true;
2218     pictureWidthLastSet = pictureWidth;
2219     pictureHeightLastSet = pictureHeight;
2220     pictureWidth = videoWidth;
2221     pictureHeight = videoHeight;
2222     // This change of picture size is invisible to app layer.
2223     // Do not update app visible params
2224     return OK;
2225 }
2226 
updateOverriddenJpegSize()2227 status_t Parameters::updateOverriddenJpegSize() {
2228     if (!pictureSizeOverriden) {
2229         ALOGV("Picture size has not been overridden. Skip checking");
2230         return OK;
2231     }
2232 
2233     pictureWidthLastSet = pictureWidth;
2234     pictureHeightLastSet = pictureHeight;
2235 
2236     if (pictureWidth <= videoWidth && pictureHeight <= videoHeight) {
2237         // Picture size is now smaller than video size. No need to override anymore
2238         return recoverOverriddenJpegSize();
2239     }
2240 
2241     pictureWidth = videoWidth;
2242     pictureHeight = videoHeight;
2243 
2244     return OK;
2245 }
2246 
recoverOverriddenJpegSize()2247 status_t Parameters::recoverOverriddenJpegSize() {
2248     if (!pictureSizeOverriden) {
2249         ALOGV("Picture size has not been overridden. Skip recovering");
2250         return OK;
2251     }
2252     pictureSizeOverriden = false;
2253     pictureWidth = pictureWidthLastSet;
2254     pictureHeight = pictureHeightLastSet;
2255     return OK;
2256 }
2257 
isJpegSizeOverridden()2258 bool Parameters::isJpegSizeOverridden() {
2259     return pictureSizeOverriden;
2260 }
2261 
useZeroShutterLag() const2262 bool Parameters::useZeroShutterLag() const {
2263     // If ZSL mode is disabled, don't use it
2264     if (!allowZslMode) return false;
2265     // If recording hint is enabled, don't do ZSL
2266     if (recordingHint) return false;
2267     // If still capture size is no bigger than preview or video size,
2268     // don't do ZSL
2269     if (pictureWidth <= previewWidth || pictureHeight <= previewHeight ||
2270             pictureWidth <= videoWidth || pictureHeight <= videoHeight) {
2271         return false;
2272     }
2273     // If still capture size is less than quarter of max, don't do ZSL
2274     if ((pictureWidth * pictureHeight) <
2275             (fastInfo.maxJpegSize.width * fastInfo.maxJpegSize.height / 4) ) {
2276         return false;
2277     }
2278     return true;
2279 }
2280 
getStateName(State state)2281 const char* Parameters::getStateName(State state) {
2282 #define CASE_ENUM_TO_CHAR(x) case x: return(#x); break;
2283     switch(state) {
2284         CASE_ENUM_TO_CHAR(DISCONNECTED)
2285         CASE_ENUM_TO_CHAR(STOPPED)
2286         CASE_ENUM_TO_CHAR(WAITING_FOR_PREVIEW_WINDOW)
2287         CASE_ENUM_TO_CHAR(PREVIEW)
2288         CASE_ENUM_TO_CHAR(RECORD)
2289         CASE_ENUM_TO_CHAR(STILL_CAPTURE)
2290         CASE_ENUM_TO_CHAR(VIDEO_SNAPSHOT)
2291         default:
2292             return "Unknown state!";
2293             break;
2294     }
2295 #undef CASE_ENUM_TO_CHAR
2296 }
2297 
formatStringToEnum(const char * format)2298 int Parameters::formatStringToEnum(const char *format) {
2299     return CameraParameters::previewFormatToEnum(format);
2300 }
2301 
formatEnumToString(int format)2302 const char* Parameters::formatEnumToString(int format) {
2303     const char *fmt;
2304     switch(format) {
2305         case HAL_PIXEL_FORMAT_YCbCr_422_SP: // NV16
2306             fmt = CameraParameters::PIXEL_FORMAT_YUV422SP;
2307             break;
2308         case HAL_PIXEL_FORMAT_YCrCb_420_SP: // NV21
2309             fmt = CameraParameters::PIXEL_FORMAT_YUV420SP;
2310             break;
2311         case HAL_PIXEL_FORMAT_YCbCr_422_I: // YUY2
2312             fmt = CameraParameters::PIXEL_FORMAT_YUV422I;
2313             break;
2314         case HAL_PIXEL_FORMAT_YV12:        // YV12
2315             fmt = CameraParameters::PIXEL_FORMAT_YUV420P;
2316             break;
2317         case HAL_PIXEL_FORMAT_RGB_565:     // RGB565
2318             fmt = CameraParameters::PIXEL_FORMAT_RGB565;
2319             break;
2320         case HAL_PIXEL_FORMAT_RGBA_8888:   // RGBA8888
2321             fmt = CameraParameters::PIXEL_FORMAT_RGBA8888;
2322             break;
2323         case HAL_PIXEL_FORMAT_RAW16:
2324             ALOGW("Raw sensor preview format requested.");
2325             fmt = CameraParameters::PIXEL_FORMAT_BAYER_RGGB;
2326             break;
2327         default:
2328             ALOGE("%s: Unknown preview format: %x",
2329                     __FUNCTION__,  format);
2330             fmt = NULL;
2331             break;
2332     }
2333     return fmt;
2334 }
2335 
wbModeStringToEnum(const char * wbMode)2336 int Parameters::wbModeStringToEnum(const char *wbMode) {
2337     return
2338         !wbMode ?
2339             ANDROID_CONTROL_AWB_MODE_AUTO :
2340         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_AUTO) ?
2341             ANDROID_CONTROL_AWB_MODE_AUTO :
2342         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_INCANDESCENT) ?
2343             ANDROID_CONTROL_AWB_MODE_INCANDESCENT :
2344         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_FLUORESCENT) ?
2345             ANDROID_CONTROL_AWB_MODE_FLUORESCENT :
2346         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_WARM_FLUORESCENT) ?
2347             ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT :
2348         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_DAYLIGHT) ?
2349             ANDROID_CONTROL_AWB_MODE_DAYLIGHT :
2350         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT) ?
2351             ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT :
2352         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_TWILIGHT) ?
2353             ANDROID_CONTROL_AWB_MODE_TWILIGHT :
2354         !strcmp(wbMode, CameraParameters::WHITE_BALANCE_SHADE) ?
2355             ANDROID_CONTROL_AWB_MODE_SHADE :
2356         -1;
2357 }
2358 
wbModeEnumToString(uint8_t wbMode)2359 const char* Parameters::wbModeEnumToString(uint8_t wbMode) {
2360     switch (wbMode) {
2361         case ANDROID_CONTROL_AWB_MODE_AUTO:
2362             return CameraParameters::WHITE_BALANCE_AUTO;
2363         case ANDROID_CONTROL_AWB_MODE_INCANDESCENT:
2364             return CameraParameters::WHITE_BALANCE_INCANDESCENT;
2365         case ANDROID_CONTROL_AWB_MODE_FLUORESCENT:
2366             return CameraParameters::WHITE_BALANCE_FLUORESCENT;
2367         case ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT:
2368             return CameraParameters::WHITE_BALANCE_WARM_FLUORESCENT;
2369         case ANDROID_CONTROL_AWB_MODE_DAYLIGHT:
2370             return CameraParameters::WHITE_BALANCE_DAYLIGHT;
2371         case ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT:
2372             return CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT;
2373         case ANDROID_CONTROL_AWB_MODE_TWILIGHT:
2374             return CameraParameters::WHITE_BALANCE_TWILIGHT;
2375         case ANDROID_CONTROL_AWB_MODE_SHADE:
2376             return CameraParameters::WHITE_BALANCE_SHADE;
2377         default:
2378             ALOGE("%s: Unknown AWB mode enum: %d",
2379                     __FUNCTION__, wbMode);
2380             return "unknown";
2381     }
2382 }
2383 
effectModeStringToEnum(const char * effectMode)2384 int Parameters::effectModeStringToEnum(const char *effectMode) {
2385     return
2386         !effectMode ?
2387             ANDROID_CONTROL_EFFECT_MODE_OFF :
2388         !strcmp(effectMode, CameraParameters::EFFECT_NONE) ?
2389             ANDROID_CONTROL_EFFECT_MODE_OFF :
2390         !strcmp(effectMode, CameraParameters::EFFECT_MONO) ?
2391             ANDROID_CONTROL_EFFECT_MODE_MONO :
2392         !strcmp(effectMode, CameraParameters::EFFECT_NEGATIVE) ?
2393             ANDROID_CONTROL_EFFECT_MODE_NEGATIVE :
2394         !strcmp(effectMode, CameraParameters::EFFECT_SOLARIZE) ?
2395             ANDROID_CONTROL_EFFECT_MODE_SOLARIZE :
2396         !strcmp(effectMode, CameraParameters::EFFECT_SEPIA) ?
2397             ANDROID_CONTROL_EFFECT_MODE_SEPIA :
2398         !strcmp(effectMode, CameraParameters::EFFECT_POSTERIZE) ?
2399             ANDROID_CONTROL_EFFECT_MODE_POSTERIZE :
2400         !strcmp(effectMode, CameraParameters::EFFECT_WHITEBOARD) ?
2401             ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD :
2402         !strcmp(effectMode, CameraParameters::EFFECT_BLACKBOARD) ?
2403             ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD :
2404         !strcmp(effectMode, CameraParameters::EFFECT_AQUA) ?
2405             ANDROID_CONTROL_EFFECT_MODE_AQUA :
2406         -1;
2407 }
2408 
abModeStringToEnum(const char * abMode)2409 int Parameters::abModeStringToEnum(const char *abMode) {
2410     return
2411         !abMode ?
2412             ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO :
2413         !strcmp(abMode, CameraParameters::ANTIBANDING_AUTO) ?
2414             ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO :
2415         !strcmp(abMode, CameraParameters::ANTIBANDING_OFF) ?
2416             ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF :
2417         !strcmp(abMode, CameraParameters::ANTIBANDING_50HZ) ?
2418             ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ :
2419         !strcmp(abMode, CameraParameters::ANTIBANDING_60HZ) ?
2420             ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ :
2421         -1;
2422 }
2423 
sceneModeStringToEnum(const char * sceneMode)2424 int Parameters::sceneModeStringToEnum(const char *sceneMode) {
2425     return
2426         !sceneMode ?
2427             ANDROID_CONTROL_SCENE_MODE_DISABLED :
2428         !strcmp(sceneMode, CameraParameters::SCENE_MODE_AUTO) ?
2429             ANDROID_CONTROL_SCENE_MODE_DISABLED :
2430         !strcmp(sceneMode, CameraParameters::SCENE_MODE_ACTION) ?
2431             ANDROID_CONTROL_SCENE_MODE_ACTION :
2432         !strcmp(sceneMode, CameraParameters::SCENE_MODE_PORTRAIT) ?
2433             ANDROID_CONTROL_SCENE_MODE_PORTRAIT :
2434         !strcmp(sceneMode, CameraParameters::SCENE_MODE_LANDSCAPE) ?
2435             ANDROID_CONTROL_SCENE_MODE_LANDSCAPE :
2436         !strcmp(sceneMode, CameraParameters::SCENE_MODE_NIGHT) ?
2437             ANDROID_CONTROL_SCENE_MODE_NIGHT :
2438         !strcmp(sceneMode, CameraParameters::SCENE_MODE_NIGHT_PORTRAIT) ?
2439             ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT :
2440         !strcmp(sceneMode, CameraParameters::SCENE_MODE_THEATRE) ?
2441             ANDROID_CONTROL_SCENE_MODE_THEATRE :
2442         !strcmp(sceneMode, CameraParameters::SCENE_MODE_BEACH) ?
2443             ANDROID_CONTROL_SCENE_MODE_BEACH :
2444         !strcmp(sceneMode, CameraParameters::SCENE_MODE_SNOW) ?
2445             ANDROID_CONTROL_SCENE_MODE_SNOW :
2446         !strcmp(sceneMode, CameraParameters::SCENE_MODE_SUNSET) ?
2447             ANDROID_CONTROL_SCENE_MODE_SUNSET :
2448         !strcmp(sceneMode, CameraParameters::SCENE_MODE_STEADYPHOTO) ?
2449             ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO :
2450         !strcmp(sceneMode, CameraParameters::SCENE_MODE_FIREWORKS) ?
2451             ANDROID_CONTROL_SCENE_MODE_FIREWORKS :
2452         !strcmp(sceneMode, CameraParameters::SCENE_MODE_SPORTS) ?
2453             ANDROID_CONTROL_SCENE_MODE_SPORTS :
2454         !strcmp(sceneMode, CameraParameters::SCENE_MODE_PARTY) ?
2455             ANDROID_CONTROL_SCENE_MODE_PARTY :
2456         !strcmp(sceneMode, CameraParameters::SCENE_MODE_CANDLELIGHT) ?
2457             ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT :
2458         !strcmp(sceneMode, CameraParameters::SCENE_MODE_BARCODE) ?
2459             ANDROID_CONTROL_SCENE_MODE_BARCODE:
2460         !strcmp(sceneMode, CameraParameters::SCENE_MODE_HDR) ?
2461             ANDROID_CONTROL_SCENE_MODE_HDR:
2462         -1;
2463 }
2464 
flashModeStringToEnum(const char * flashMode)2465 Parameters::Parameters::flashMode_t Parameters::flashModeStringToEnum(
2466         const char *flashMode) {
2467     return
2468         !flashMode ?
2469             Parameters::FLASH_MODE_OFF :
2470         !strcmp(flashMode, CameraParameters::FLASH_MODE_OFF) ?
2471             Parameters::FLASH_MODE_OFF :
2472         !strcmp(flashMode, CameraParameters::FLASH_MODE_AUTO) ?
2473             Parameters::FLASH_MODE_AUTO :
2474         !strcmp(flashMode, CameraParameters::FLASH_MODE_ON) ?
2475             Parameters::FLASH_MODE_ON :
2476         !strcmp(flashMode, CameraParameters::FLASH_MODE_RED_EYE) ?
2477             Parameters::FLASH_MODE_RED_EYE :
2478         !strcmp(flashMode, CameraParameters::FLASH_MODE_TORCH) ?
2479             Parameters::FLASH_MODE_TORCH :
2480         Parameters::FLASH_MODE_INVALID;
2481 }
2482 
flashModeEnumToString(flashMode_t flashMode)2483 const char *Parameters::flashModeEnumToString(flashMode_t flashMode) {
2484     switch (flashMode) {
2485         case FLASH_MODE_OFF:
2486             return CameraParameters::FLASH_MODE_OFF;
2487         case FLASH_MODE_AUTO:
2488             return CameraParameters::FLASH_MODE_AUTO;
2489         case FLASH_MODE_ON:
2490             return CameraParameters::FLASH_MODE_ON;
2491         case FLASH_MODE_RED_EYE:
2492             return CameraParameters::FLASH_MODE_RED_EYE;
2493         case FLASH_MODE_TORCH:
2494             return CameraParameters::FLASH_MODE_TORCH;
2495         default:
2496             ALOGE("%s: Unknown flash mode enum %d",
2497                     __FUNCTION__, flashMode);
2498             return "unknown";
2499     }
2500 }
2501 
focusModeStringToEnum(const char * focusMode)2502 Parameters::Parameters::focusMode_t Parameters::focusModeStringToEnum(
2503         const char *focusMode) {
2504     return
2505         !focusMode ?
2506             Parameters::FOCUS_MODE_INVALID :
2507         !strcmp(focusMode, CameraParameters::FOCUS_MODE_AUTO) ?
2508             Parameters::FOCUS_MODE_AUTO :
2509         !strcmp(focusMode, CameraParameters::FOCUS_MODE_INFINITY) ?
2510             Parameters::FOCUS_MODE_INFINITY :
2511         !strcmp(focusMode, CameraParameters::FOCUS_MODE_MACRO) ?
2512             Parameters::FOCUS_MODE_MACRO :
2513         !strcmp(focusMode, CameraParameters::FOCUS_MODE_FIXED) ?
2514             Parameters::FOCUS_MODE_FIXED :
2515         !strcmp(focusMode, CameraParameters::FOCUS_MODE_EDOF) ?
2516             Parameters::FOCUS_MODE_EDOF :
2517         !strcmp(focusMode, CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO) ?
2518             Parameters::FOCUS_MODE_CONTINUOUS_VIDEO :
2519         !strcmp(focusMode, CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE) ?
2520             Parameters::FOCUS_MODE_CONTINUOUS_PICTURE :
2521         Parameters::FOCUS_MODE_INVALID;
2522 }
2523 
focusModeEnumToString(focusMode_t focusMode)2524 const char *Parameters::focusModeEnumToString(focusMode_t focusMode) {
2525     switch (focusMode) {
2526         case FOCUS_MODE_AUTO:
2527             return CameraParameters::FOCUS_MODE_AUTO;
2528         case FOCUS_MODE_MACRO:
2529             return CameraParameters::FOCUS_MODE_MACRO;
2530         case FOCUS_MODE_CONTINUOUS_VIDEO:
2531             return CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO;
2532         case FOCUS_MODE_CONTINUOUS_PICTURE:
2533             return CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE;
2534         case FOCUS_MODE_EDOF:
2535             return CameraParameters::FOCUS_MODE_EDOF;
2536         case FOCUS_MODE_INFINITY:
2537             return CameraParameters::FOCUS_MODE_INFINITY;
2538         case FOCUS_MODE_FIXED:
2539             return CameraParameters::FOCUS_MODE_FIXED;
2540         default:
2541             ALOGE("%s: Unknown focus mode enum: %d",
2542                     __FUNCTION__, focusMode);
2543             return "unknown";
2544     }
2545 }
2546 
parseAreas(const char * areasCStr,Vector<Parameters::Area> * areas)2547 status_t Parameters::parseAreas(const char *areasCStr,
2548         Vector<Parameters::Area> *areas) {
2549     static const size_t NUM_FIELDS = 5;
2550     areas->clear();
2551     if (areasCStr == NULL) {
2552         // If no key exists, use default (0,0,0,0,0)
2553         areas->push();
2554         return OK;
2555     }
2556     String8 areasStr(areasCStr);
2557     ssize_t areaStart = areasStr.find("(", 0) + 1;
2558     while (areaStart != 0) {
2559         const char* area = areasStr.string() + areaStart;
2560         char *numEnd;
2561         int vals[NUM_FIELDS];
2562         for (size_t i = 0; i < NUM_FIELDS; i++) {
2563             errno = 0;
2564             vals[i] = strtol(area, &numEnd, 10);
2565             if (errno || numEnd == area) return BAD_VALUE;
2566             area = numEnd + 1;
2567         }
2568         areas->push(Parameters::Area(
2569             vals[0], vals[1], vals[2], vals[3], vals[4]) );
2570         areaStart = areasStr.find("(", areaStart) + 1;
2571     }
2572     return OK;
2573 }
2574 
validateAreas(const Vector<Parameters::Area> & areas,size_t maxRegions,AreaKind areaKind) const2575 status_t Parameters::validateAreas(const Vector<Parameters::Area> &areas,
2576                                       size_t maxRegions,
2577                                       AreaKind areaKind) const {
2578     // Definition of valid area can be found in
2579     // include/camera/CameraParameters.h
2580     if (areas.size() == 0) return BAD_VALUE;
2581     if (areas.size() == 1) {
2582         if (areas[0].left == 0 &&
2583                 areas[0].top == 0 &&
2584                 areas[0].right == 0 &&
2585                 areas[0].bottom == 0 &&
2586                 areas[0].weight == 0) {
2587             // Single (0,0,0,0,0) entry is always valid (== driver decides)
2588             return OK;
2589         }
2590     }
2591 
2592     // fixed focus can only set (0,0,0,0,0) focus area
2593     if (areaKind == AREA_KIND_FOCUS && focusMode == FOCUS_MODE_FIXED) {
2594         return BAD_VALUE;
2595     }
2596 
2597     if (areas.size() > maxRegions) {
2598         ALOGE("%s: Too many areas requested: %zu",
2599                 __FUNCTION__, areas.size());
2600         return BAD_VALUE;
2601     }
2602 
2603     for (Vector<Parameters::Area>::const_iterator a = areas.begin();
2604          a != areas.end(); a++) {
2605         if (a->weight < 1 || a->weight > 1000) return BAD_VALUE;
2606         if (a->left < -1000 || a->left > 1000) return BAD_VALUE;
2607         if (a->top < -1000 || a->top > 1000) return BAD_VALUE;
2608         if (a->right < -1000 || a->right > 1000) return BAD_VALUE;
2609         if (a->bottom < -1000 || a->bottom > 1000) return BAD_VALUE;
2610         if (a->left >= a->right) return BAD_VALUE;
2611         if (a->top >= a->bottom) return BAD_VALUE;
2612     }
2613     return OK;
2614 }
2615 
boolFromString(const char * boolStr)2616 bool Parameters::boolFromString(const char *boolStr) {
2617     return !boolStr ? false :
2618         !strcmp(boolStr, CameraParameters::TRUE) ? true :
2619         false;
2620 }
2621 
degToTransform(int degrees,bool mirror)2622 int Parameters::degToTransform(int degrees, bool mirror) {
2623     if (!mirror) {
2624         if (degrees == 0) return 0;
2625         else if (degrees == 90) return HAL_TRANSFORM_ROT_90;
2626         else if (degrees == 180) return HAL_TRANSFORM_ROT_180;
2627         else if (degrees == 270) return HAL_TRANSFORM_ROT_270;
2628     } else {  // Do mirror (horizontal flip)
2629         if (degrees == 0) {           // FLIP_H and ROT_0
2630             return HAL_TRANSFORM_FLIP_H;
2631         } else if (degrees == 90) {   // FLIP_H and ROT_90
2632             return HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90;
2633         } else if (degrees == 180) {  // FLIP_H and ROT_180
2634             return HAL_TRANSFORM_FLIP_V;
2635         } else if (degrees == 270) {  // FLIP_H and ROT_270
2636             return HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90;
2637         }
2638     }
2639     ALOGE("%s: Bad input: %d", __FUNCTION__, degrees);
2640     return -1;
2641 }
2642 
cropXToArray(int x) const2643 int Parameters::cropXToArray(int x) const {
2644     ALOG_ASSERT(x >= 0, "Crop-relative X coordinate = '%d' is out of bounds"
2645                          "(lower = 0)", x);
2646 
2647     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2648     ALOG_ASSERT(x < previewCrop.width, "Crop-relative X coordinate = '%d' "
2649                     "is out of bounds (upper = %f)", x, previewCrop.width);
2650 
2651     int ret = x + previewCrop.left;
2652 
2653     ALOG_ASSERT( (ret >= 0 && ret < fastInfo.arrayWidth),
2654         "Calculated pixel array value X = '%d' is out of bounds (upper = %d)",
2655         ret, fastInfo.arrayWidth);
2656     return ret;
2657 }
2658 
cropYToArray(int y) const2659 int Parameters::cropYToArray(int y) const {
2660     ALOG_ASSERT(y >= 0, "Crop-relative Y coordinate = '%d' is out of bounds "
2661         "(lower = 0)", y);
2662 
2663     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2664     ALOG_ASSERT(y < previewCrop.height, "Crop-relative Y coordinate = '%d' is "
2665                 "out of bounds (upper = %f)", y, previewCrop.height);
2666 
2667     int ret = y + previewCrop.top;
2668 
2669     ALOG_ASSERT( (ret >= 0 && ret < fastInfo.arrayHeight),
2670         "Calculated pixel array value Y = '%d' is out of bounds (upper = %d)",
2671         ret, fastInfo.arrayHeight);
2672 
2673     return ret;
2674 
2675 }
2676 
normalizedXToCrop(int x) const2677 int Parameters::normalizedXToCrop(int x) const {
2678     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2679     return (x + 1000) * (previewCrop.width - 1) / 2000;
2680 }
2681 
normalizedYToCrop(int y) const2682 int Parameters::normalizedYToCrop(int y) const {
2683     CropRegion previewCrop = calculateCropRegion(/*previewOnly*/ true);
2684     return (y + 1000) * (previewCrop.height - 1) / 2000;
2685 }
2686 
normalizedXToArray(int x) const2687 int Parameters::normalizedXToArray(int x) const {
2688 
2689     // Work-around for HAL pre-scaling the coordinates themselves
2690     if (quirks.meteringCropRegion) {
2691         return (x + 1000) * (fastInfo.arrayWidth - 1) / 2000;
2692     }
2693 
2694     return cropXToArray(normalizedXToCrop(x));
2695 }
2696 
normalizedYToArray(int y) const2697 int Parameters::normalizedYToArray(int y) const {
2698     // Work-around for HAL pre-scaling the coordinates themselves
2699     if (quirks.meteringCropRegion) {
2700         return (y + 1000) * (fastInfo.arrayHeight - 1) / 2000;
2701     }
2702 
2703     return cropYToArray(normalizedYToCrop(y));
2704 }
2705 
2706 
calculatePreviewCrop(const CropRegion & scalerCrop) const2707 Parameters::CropRegion Parameters::calculatePreviewCrop(
2708         const CropRegion &scalerCrop) const {
2709     float left, top, width, height;
2710     float previewAspect = static_cast<float>(previewWidth) / previewHeight;
2711     float cropAspect = scalerCrop.width / scalerCrop.height;
2712 
2713     if (previewAspect > cropAspect) {
2714         width = scalerCrop.width;
2715         height = cropAspect * scalerCrop.height / previewAspect;
2716 
2717         left = scalerCrop.left;
2718         top = scalerCrop.top + (scalerCrop.height - height) / 2;
2719     } else {
2720         width = previewAspect * scalerCrop.width / cropAspect;
2721         height = scalerCrop.height;
2722 
2723         left = scalerCrop.left + (scalerCrop.width - width) / 2;
2724         top = scalerCrop.top;
2725     }
2726 
2727     CropRegion previewCrop = {left, top, width, height};
2728 
2729     return previewCrop;
2730 }
2731 
arrayXToNormalizedWithCrop(int x,const CropRegion & scalerCrop) const2732 int Parameters::arrayXToNormalizedWithCrop(int x,
2733         const CropRegion &scalerCrop) const {
2734     // Work-around for HAL pre-scaling the coordinates themselves
2735     if (quirks.meteringCropRegion) {
2736         return x * 2000 / (fastInfo.arrayWidth - 1) - 1000;
2737     } else {
2738         CropRegion previewCrop = calculatePreviewCrop(scalerCrop);
2739         return (x - previewCrop.left) * 2000 / (previewCrop.width - 1) - 1000;
2740     }
2741 }
2742 
arrayYToNormalizedWithCrop(int y,const CropRegion & scalerCrop) const2743 int Parameters::arrayYToNormalizedWithCrop(int y,
2744         const CropRegion &scalerCrop) const {
2745     // Work-around for HAL pre-scaling the coordinates themselves
2746     if (quirks.meteringCropRegion) {
2747         return y * 2000 / (fastInfo.arrayHeight - 1) - 1000;
2748     } else {
2749         CropRegion previewCrop = calculatePreviewCrop(scalerCrop);
2750         return (y - previewCrop.top) * 2000 / (previewCrop.height - 1) - 1000;
2751     }
2752 }
2753 
getFilteredSizes(Size limit,Vector<Size> * sizes)2754 status_t Parameters::getFilteredSizes(Size limit, Vector<Size> *sizes) {
2755     if (info == NULL) {
2756         ALOGE("%s: Static metadata is not initialized", __FUNCTION__);
2757         return NO_INIT;
2758     }
2759     if (sizes == NULL) {
2760         ALOGE("%s: Input size is null", __FUNCTION__);
2761         return BAD_VALUE;
2762     }
2763     sizes->clear();
2764 
2765     if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2766         Vector<StreamConfiguration> scs = getStreamConfigurations();
2767         for (size_t i=0; i < scs.size(); i++) {
2768             const StreamConfiguration &sc = scs[i];
2769             if (sc.isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT &&
2770                     sc.format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
2771                     sc.width <= limit.width && sc.height <= limit.height) {
2772                 Size sz = {sc.width, sc.height};
2773                 sizes->push(sz);
2774             }
2775         }
2776     } else {
2777         const size_t SIZE_COUNT = sizeof(Size) / sizeof(int);
2778         camera_metadata_ro_entry_t availableProcessedSizes =
2779             staticInfo(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES, SIZE_COUNT);
2780         if (availableProcessedSizes.count < SIZE_COUNT) return BAD_VALUE;
2781 
2782         Size filteredSize;
2783         for (size_t i = 0; i < availableProcessedSizes.count; i += SIZE_COUNT) {
2784             filteredSize.width = availableProcessedSizes.data.i32[i];
2785             filteredSize.height = availableProcessedSizes.data.i32[i+1];
2786                 // Need skip the preview sizes that are too large.
2787                 if (filteredSize.width <= limit.width &&
2788                         filteredSize.height <= limit.height) {
2789                     sizes->push(filteredSize);
2790                 }
2791         }
2792     }
2793 
2794     if (sizes->isEmpty()) {
2795         ALOGE("generated preview size list is empty!!");
2796         return BAD_VALUE;
2797     }
2798     return OK;
2799 }
2800 
getMaxSizeForRatio(float ratio,const int32_t * sizeArray,size_t count)2801 Parameters::Size Parameters::getMaxSizeForRatio(
2802         float ratio, const int32_t* sizeArray, size_t count) {
2803     ALOG_ASSERT(sizeArray != NULL, "size array shouldn't be NULL");
2804     ALOG_ASSERT(count >= 2 && count % 2 == 0, "count must be a positive even number");
2805 
2806     Size maxSize = {0, 0};
2807     for (size_t i = 0; i < count; i += 2) {
2808         if (sizeArray[i] > 0 && sizeArray[i+1] > 0) {
2809             float curRatio = static_cast<float>(sizeArray[i]) / sizeArray[i+1];
2810             if (fabs(curRatio - ratio) < ASPECT_RATIO_TOLERANCE && maxSize.width < sizeArray[i]) {
2811                 maxSize.width = sizeArray[i];
2812                 maxSize.height = sizeArray[i+1];
2813             }
2814         }
2815     }
2816 
2817     if (maxSize.width == 0 || maxSize.height == 0) {
2818         maxSize.width = sizeArray[0];
2819         maxSize.height = sizeArray[1];
2820         ALOGW("Unable to find the size to match the given aspect ratio %f."
2821                 "Fall back to %d x %d", ratio, maxSize.width, maxSize.height);
2822     }
2823 
2824     return maxSize;
2825 }
2826 
getMaxSize(const Vector<Parameters::Size> & sizes)2827 Parameters::Size Parameters::getMaxSize(const Vector<Parameters::Size> &sizes) {
2828     Size maxSize = {-1, -1};
2829     for (size_t i = 0; i < sizes.size(); i++) {
2830         if (sizes[i].width > maxSize.width ||
2831                 (sizes[i].width == maxSize.width && sizes[i].height > maxSize.height )) {
2832             maxSize = sizes[i];
2833         }
2834     }
2835     return maxSize;
2836 }
2837 
getStreamConfigurations()2838 Vector<Parameters::StreamConfiguration> Parameters::getStreamConfigurations() {
2839     const int STREAM_CONFIGURATION_SIZE = 4;
2840     const int STREAM_FORMAT_OFFSET = 0;
2841     const int STREAM_WIDTH_OFFSET = 1;
2842     const int STREAM_HEIGHT_OFFSET = 2;
2843     const int STREAM_IS_INPUT_OFFSET = 3;
2844     Vector<StreamConfiguration> scs;
2845     if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
2846         ALOGE("StreamConfiguration is only valid after device HAL 3.2!");
2847         return scs;
2848     }
2849 
2850     camera_metadata_ro_entry_t availableStreamConfigs =
2851                 staticInfo(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
2852     for (size_t i = 0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
2853         int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
2854         int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
2855         int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
2856         int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
2857         StreamConfiguration sc = {format, width, height, isInput};
2858         scs.add(sc);
2859     }
2860     return scs;
2861 }
2862 
getJpegStreamMinFrameDurationNs(Parameters::Size size)2863 int64_t Parameters::getJpegStreamMinFrameDurationNs(Parameters::Size size) {
2864     if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2865         return getMinFrameDurationNs(size, HAL_PIXEL_FORMAT_BLOB);
2866     } else {
2867         Vector<Size> availableJpegSizes = getAvailableJpegSizes();
2868         size_t streamIdx = availableJpegSizes.size();
2869         for (size_t i = 0; i < availableJpegSizes.size(); i++) {
2870             if (availableJpegSizes[i].width == size.width &&
2871                     availableJpegSizes[i].height == size.height) {
2872                 streamIdx = i;
2873                 break;
2874             }
2875         }
2876         if (streamIdx != availableJpegSizes.size()) {
2877             camera_metadata_ro_entry_t jpegMinDurations =
2878                     staticInfo(ANDROID_SCALER_AVAILABLE_JPEG_MIN_DURATIONS);
2879             if (streamIdx < jpegMinDurations.count) {
2880                 return jpegMinDurations.data.i64[streamIdx];
2881             }
2882         }
2883     }
2884     ALOGE("%s: cannot find min frame duration for jpeg size %dx%d",
2885             __FUNCTION__, size.width, size.height);
2886     return -1;
2887 }
2888 
getMinFrameDurationNs(Parameters::Size size,int fmt)2889 int64_t Parameters::getMinFrameDurationNs(Parameters::Size size, int fmt) {
2890     if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
2891         ALOGE("Min frame duration for HAL 3.1 or lower is not supported");
2892         return -1;
2893     }
2894 
2895     const int STREAM_DURATION_SIZE = 4;
2896     const int STREAM_FORMAT_OFFSET = 0;
2897     const int STREAM_WIDTH_OFFSET = 1;
2898     const int STREAM_HEIGHT_OFFSET = 2;
2899     const int STREAM_DURATION_OFFSET = 3;
2900     camera_metadata_ro_entry_t availableStreamMinDurations =
2901                 staticInfo(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
2902     for (size_t i = 0; i < availableStreamMinDurations.count; i+= STREAM_DURATION_SIZE) {
2903         int64_t format = availableStreamMinDurations.data.i64[i + STREAM_FORMAT_OFFSET];
2904         int64_t width = availableStreamMinDurations.data.i64[i + STREAM_WIDTH_OFFSET];
2905         int64_t height = availableStreamMinDurations.data.i64[i + STREAM_HEIGHT_OFFSET];
2906         int64_t duration = availableStreamMinDurations.data.i64[i + STREAM_DURATION_OFFSET];
2907         if (format == fmt && width == size.width && height == size.height) {
2908             return duration;
2909         }
2910     }
2911 
2912     return -1;
2913 }
2914 
isFpsSupported(const Vector<Size> & sizes,int format,int32_t fps)2915 bool Parameters::isFpsSupported(const Vector<Size> &sizes, int format, int32_t fps) {
2916     // Skip the check for older HAL version, as the min duration is not supported.
2917     if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
2918         return true;
2919     }
2920 
2921     // Get min frame duration for each size and check if the given fps range can be supported.
2922     const int32_t FPS_MARGIN = 1;
2923     for (size_t i = 0 ; i < sizes.size(); i++) {
2924         int64_t minFrameDuration = getMinFrameDurationNs(sizes[i], format);
2925         if (minFrameDuration <= 0) {
2926             ALOGE("Min frame duration (%" PRId64") for size (%dx%d) and format 0x%x is wrong!",
2927                 minFrameDuration, sizes[i].width, sizes[i].height, format);
2928             return false;
2929         }
2930         int32_t maxSupportedFps = 1e9 / minFrameDuration;
2931         // Add some margin here for the case where the hal supports 29.xxxfps.
2932         maxSupportedFps += FPS_MARGIN;
2933         if (fps > maxSupportedFps) {
2934             return false;
2935         }
2936     }
2937     return true;
2938 }
2939 
getAvailableOutputFormats()2940 SortedVector<int32_t> Parameters::getAvailableOutputFormats() {
2941     SortedVector<int32_t> outputFormats; // Non-duplicated output formats
2942     if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2943         Vector<StreamConfiguration> scs = getStreamConfigurations();
2944         for (size_t i = 0; i < scs.size(); i++) {
2945             const StreamConfiguration &sc = scs[i];
2946             if (sc.isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT) {
2947                 outputFormats.add(sc.format);
2948             }
2949         }
2950     } else {
2951         camera_metadata_ro_entry_t availableFormats = staticInfo(ANDROID_SCALER_AVAILABLE_FORMATS);
2952         for (size_t i = 0; i < availableFormats.count; i++) {
2953             outputFormats.add(availableFormats.data.i32[i]);
2954         }
2955     }
2956     return outputFormats;
2957 }
2958 
getAvailableJpegSizes()2959 Vector<Parameters::Size> Parameters::getAvailableJpegSizes() {
2960     Vector<Parameters::Size> jpegSizes;
2961     if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2962         Vector<StreamConfiguration> scs = getStreamConfigurations();
2963         for (size_t i = 0; i < scs.size(); i++) {
2964             const StreamConfiguration &sc = scs[i];
2965             if (sc.isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT &&
2966                     sc.format == HAL_PIXEL_FORMAT_BLOB) {
2967                 Size sz = {sc.width, sc.height};
2968                 jpegSizes.add(sz);
2969             }
2970         }
2971     } else {
2972         const int JPEG_SIZE_ENTRY_COUNT = 2;
2973         const int WIDTH_OFFSET = 0;
2974         const int HEIGHT_OFFSET = 1;
2975         camera_metadata_ro_entry_t availableJpegSizes =
2976             staticInfo(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
2977         for (size_t i = 0; i < availableJpegSizes.count; i+= JPEG_SIZE_ENTRY_COUNT) {
2978             int width = availableJpegSizes.data.i32[i + WIDTH_OFFSET];
2979             int height = availableJpegSizes.data.i32[i + HEIGHT_OFFSET];
2980             Size sz = {width, height};
2981             jpegSizes.add(sz);
2982         }
2983     }
2984     return jpegSizes;
2985 }
2986 
calculateCropRegion(bool previewOnly) const2987 Parameters::CropRegion Parameters::calculateCropRegion(bool previewOnly) const {
2988 
2989     float zoomLeft, zoomTop, zoomWidth, zoomHeight;
2990 
2991     // Need to convert zoom index into a crop rectangle. The rectangle is
2992     // chosen to maximize its area on the sensor
2993 
2994     camera_metadata_ro_entry_t maxDigitalZoom =
2995             staticInfo(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
2996     // For each zoom step by how many pixels more do we change the zoom
2997     float zoomIncrement = (maxDigitalZoom.data.f[0] - 1) /
2998             (NUM_ZOOM_STEPS-1);
2999     // The desired activeAreaWidth/cropAreaWidth ratio (or height if h>w)
3000     // via interpolating zoom step into a zoom ratio
3001     float zoomRatio = 1 + zoomIncrement * zoom;
3002     ALOG_ASSERT( (zoomRatio >= 1.f && zoomRatio <= maxDigitalZoom.data.f[0]),
3003         "Zoom ratio calculated out of bounds. Expected 1 - %f, actual: %f",
3004         maxDigitalZoom.data.f[0], zoomRatio);
3005 
3006     ALOGV("Zoom maxDigital=%f, increment=%f, ratio=%f, previewWidth=%d, "
3007           "previewHeight=%d, activeWidth=%d, activeHeight=%d",
3008           maxDigitalZoom.data.f[0], zoomIncrement, zoomRatio, previewWidth,
3009           previewHeight, fastInfo.arrayWidth, fastInfo.arrayHeight);
3010 
3011     if (previewOnly) {
3012         // Calculate a tight crop region for the preview stream only
3013         float previewRatio = static_cast<float>(previewWidth) / previewHeight;
3014 
3015         /* Ensure that the width/height never go out of bounds
3016          * by scaling across a diffent dimension if an out-of-bounds
3017          * possibility exists.
3018          *
3019          * e.g. if the previewratio < arrayratio and e.g. zoomratio = 1.0, then by
3020          * calculating the zoomWidth from zoomHeight we'll actually get a
3021          * zoomheight > arrayheight
3022          */
3023         float arrayRatio = 1.f * fastInfo.arrayWidth / fastInfo.arrayHeight;
3024         if (previewRatio >= arrayRatio) {
3025             // Adjust the height based on the width
3026             zoomWidth =  fastInfo.arrayWidth / zoomRatio;
3027             zoomHeight = zoomWidth *
3028                     previewHeight / previewWidth;
3029 
3030         } else {
3031             // Adjust the width based on the height
3032             zoomHeight = fastInfo.arrayHeight / zoomRatio;
3033             zoomWidth = zoomHeight *
3034                     previewWidth / previewHeight;
3035         }
3036     } else {
3037         // Calculate the global crop region with a shape matching the active
3038         // array.
3039         zoomWidth = fastInfo.arrayWidth / zoomRatio;
3040         zoomHeight = fastInfo.arrayHeight / zoomRatio;
3041     }
3042 
3043     // center the zoom area within the active area
3044     zoomLeft = (fastInfo.arrayWidth - zoomWidth) / 2;
3045     zoomTop = (fastInfo.arrayHeight - zoomHeight) / 2;
3046 
3047     ALOGV("Crop region calculated (x=%d,y=%d,w=%f,h=%f) for zoom=%d",
3048         (int32_t)zoomLeft, (int32_t)zoomTop, zoomWidth, zoomHeight, this->zoom);
3049 
3050     CropRegion crop = { zoomLeft, zoomTop, zoomWidth, zoomHeight };
3051     return crop;
3052 }
3053 
calculatePictureFovs(float * horizFov,float * vertFov) const3054 status_t Parameters::calculatePictureFovs(float *horizFov, float *vertFov)
3055         const {
3056     camera_metadata_ro_entry_t sensorSize =
3057             staticInfo(ANDROID_SENSOR_INFO_PHYSICAL_SIZE, 2, 2);
3058     if (!sensorSize.count) return NO_INIT;
3059 
3060     camera_metadata_ro_entry_t pixelArraySize =
3061             staticInfo(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE, 2, 2);
3062     if (!pixelArraySize.count) return NO_INIT;
3063 
3064     float arrayAspect = static_cast<float>(fastInfo.arrayWidth) /
3065             fastInfo.arrayHeight;
3066     float stillAspect = static_cast<float>(pictureWidth) / pictureHeight;
3067     ALOGV("Array aspect: %f, still aspect: %f", arrayAspect, stillAspect);
3068 
3069     // The crop factors from the full sensor array to the still picture crop
3070     // region
3071     float horizCropFactor = 1.f;
3072     float vertCropFactor = 1.f;
3073 
3074     /**
3075      * Need to calculate the still image field of view based on the total pixel
3076      * array field of view, and the relative aspect ratios of the pixel array
3077      * and output streams.
3078      *
3079      * Special treatment for quirky definition of crop region and relative
3080      * stream cropping.
3081      */
3082     if (quirks.meteringCropRegion) {
3083         // Use max of preview and video as first crop
3084         float previewAspect = static_cast<float>(previewWidth) / previewHeight;
3085         float videoAspect = static_cast<float>(videoWidth) / videoHeight;
3086         if (videoAspect > previewAspect) {
3087             previewAspect = videoAspect;
3088         }
3089         // First crop sensor to preview aspect ratio
3090         if (arrayAspect < previewAspect) {
3091             vertCropFactor = arrayAspect / previewAspect;
3092         } else {
3093             horizCropFactor = previewAspect / arrayAspect;
3094         }
3095         // Second crop to still aspect ratio
3096         if (stillAspect < previewAspect) {
3097             horizCropFactor *= stillAspect / previewAspect;
3098         } else {
3099             vertCropFactor *= previewAspect / stillAspect;
3100         }
3101     } else {
3102         /**
3103          * Crop are just a function of just the still/array relative aspect
3104          * ratios. Since each stream will maximize its area within the crop
3105          * region, and for FOV we assume a full-sensor crop region, we only ever
3106          * crop the FOV either vertically or horizontally, never both.
3107          */
3108         horizCropFactor = (arrayAspect > stillAspect) ?
3109                 (stillAspect / arrayAspect) : 1.f;
3110         vertCropFactor = (arrayAspect < stillAspect) ?
3111                 (arrayAspect / stillAspect) : 1.f;
3112     }
3113 
3114     /**
3115      * Convert the crop factors w.r.t the active array size to the crop factors
3116      * w.r.t the pixel array size.
3117      */
3118     horizCropFactor *= (static_cast<float>(fastInfo.arrayWidth) /
3119                             pixelArraySize.data.i32[0]);
3120     vertCropFactor *= (static_cast<float>(fastInfo.arrayHeight) /
3121                             pixelArraySize.data.i32[1]);
3122 
3123     ALOGV("Horiz crop factor: %f, vert crop fact: %f",
3124             horizCropFactor, vertCropFactor);
3125     /**
3126      * Basic field of view formula is:
3127      *   angle of view = 2 * arctangent ( d / 2f )
3128      * where d is the physical sensor dimension of interest, and f is
3129      * the focal length. This only applies to rectilinear sensors, for focusing
3130      * at distances >> f, etc.
3131      */
3132     if (horizFov != NULL) {
3133         *horizFov = 180 / M_PI * 2 *
3134                 atanf(horizCropFactor * sensorSize.data.f[0] /
3135                         (2 * fastInfo.minFocalLength));
3136     }
3137     if (vertFov != NULL) {
3138         *vertFov = 180 / M_PI * 2 *
3139                 atanf(vertCropFactor * sensorSize.data.f[1] /
3140                         (2 * fastInfo.minFocalLength));
3141     }
3142     return OK;
3143 }
3144 
fpsFromRange(int32_t,int32_t max) const3145 int32_t Parameters::fpsFromRange(int32_t /*min*/, int32_t max) const {
3146     return max;
3147 }
3148 
3149 }; // namespace camera2
3150 }; // namespace android
3151