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