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