LegacyRequestMapper.java revision 6a7d8c42890451e01ca7b4baba03d430808265bc
1/*
2 * Copyright (C) 2014 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
17package android.hardware.camera2.legacy;
18
19import android.graphics.Rect;
20import android.hardware.Camera;
21import android.hardware.Camera.Parameters;
22import android.hardware.camera2.CameraCharacteristics;
23import android.hardware.camera2.CaptureRequest;
24import android.hardware.camera2.params.MeteringRectangle;
25import android.hardware.camera2.utils.ListUtils;
26import android.hardware.camera2.utils.ParamsUtils;
27import android.util.Log;
28import android.util.Range;
29import android.util.Size;
30
31import java.util.ArrayList;
32import java.util.Arrays;
33import java.util.List;
34import java.util.Objects;
35
36import static com.android.internal.util.Preconditions.*;
37import static android.hardware.camera2.CaptureRequest.*;
38
39/**
40 * Provide legacy-specific implementations of camera2 CaptureRequest for legacy devices.
41 */
42@SuppressWarnings("deprecation")
43public class LegacyRequestMapper {
44    private static final String TAG = "LegacyRequestMapper";
45    private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
46
47    /**
48     * Set the legacy parameters using the {@link LegacyRequest legacy request}.
49     *
50     * <p>The legacy request's parameters are changed as a side effect of calling this
51     * method.</p>
52     *
53     * @param legacyRequest a non-{@code null} legacy request
54     */
55    public static void convertRequestMetadata(LegacyRequest legacyRequest) {
56        CameraCharacteristics characteristics = legacyRequest.characteristics;
57        CaptureRequest request = legacyRequest.captureRequest;
58        Size previewSize = legacyRequest.previewSize;
59        Camera.Parameters params = legacyRequest.parameters;
60
61        Rect activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
62
63        /*
64         * scaler.cropRegion
65         */
66        ParameterUtils.ZoomData zoomData;
67        {
68            zoomData = ParameterUtils.convertScalerCropRegion(activeArray,
69                    request.get(SCALER_CROP_REGION),
70                    previewSize,
71                    params);
72
73            if (params.isZoomSupported()) {
74                params.setZoom(zoomData.zoomIndex);
75            } else if (VERBOSE) {
76                Log.v(TAG, "convertRequestToMetadata - zoom is not supported");
77            }
78        }
79
80
81        /*
82         * control.ae*
83         */
84        // control.aeAntibandingMode
85        {
86        String legacyMode;
87            Integer antiBandingMode = request.get(CONTROL_AE_ANTIBANDING_MODE);
88            if (antiBandingMode != null) {
89                legacyMode = convertAeAntiBandingModeToLegacy(antiBandingMode);
90            } else {
91                legacyMode = ListUtils.listSelectFirstFrom(params.getSupportedAntibanding(),
92                        new String[] {
93                            Parameters.ANTIBANDING_AUTO,
94                            Parameters.ANTIBANDING_OFF,
95                            Parameters.ANTIBANDING_50HZ,
96                            Parameters.ANTIBANDING_60HZ,
97                        });
98            }
99
100            if (legacyMode != null) {
101                params.setAntibanding(legacyMode);
102            }
103        }
104
105        /*
106         * control.aeRegions, afRegions
107         */
108        {
109            // aeRegions
110            {
111                // Use aeRegions if available, fall back to using awbRegions if present
112                MeteringRectangle[] aeRegions = request.get(CONTROL_AE_REGIONS);
113                if (request.get(CONTROL_AWB_REGIONS) != null) {
114                    Log.w(TAG, "convertRequestMetadata - control.awbRegions setting is not " +
115                            "supported, ignoring value");
116                }
117                int maxNumMeteringAreas = params.getMaxNumMeteringAreas();
118                List<Camera.Area> meteringAreaList = convertMeteringRegionsToLegacy(
119                        activeArray, zoomData, aeRegions, maxNumMeteringAreas,
120                        /*regionName*/"AE");
121
122                params.setMeteringAreas(meteringAreaList);
123            }
124
125            // afRegions
126            {
127                MeteringRectangle[] afRegions = request.get(CONTROL_AF_REGIONS);
128                int maxNumFocusAreas = params.getMaxNumFocusAreas();
129                List<Camera.Area> focusAreaList = convertMeteringRegionsToLegacy(
130                        activeArray, zoomData, afRegions, maxNumFocusAreas,
131                        /*regionName*/"AF");
132
133                params.setFocusAreas(focusAreaList);
134            }
135        }
136
137        // control.aeTargetFpsRange
138        Range<Integer> aeFpsRange = request.get(CONTROL_AE_TARGET_FPS_RANGE);
139        if (aeFpsRange != null) {
140            int[] legacyFps = convertAeFpsRangeToLegacy(aeFpsRange);
141
142            // TODO - Should we enforce that all HAL1 devices must include (30, 30) FPS range?
143            boolean supported = false;
144            for(int[] range : params.getSupportedPreviewFpsRange()) {
145                if (legacyFps[0] == range[0] && legacyFps[1] == range[1]) {
146                    supported = true;
147                    break;
148                }
149            }
150            if (supported) {
151                params.setPreviewFpsRange(legacyFps[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
152                        legacyFps[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
153                params.setRecordingHint(false);
154            } else {
155                Log.w(TAG, "Unsupported FPS range set [" + legacyFps[0] + "," + legacyFps[1] + "]");
156                params.setRecordingHint(true);
157            }
158        }
159
160        /*
161         * control
162         */
163
164        // control.aeExposureCompensation
165        {
166            Range<Integer> compensationRange =
167                    characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE);
168            int compensation = ParamsUtils.getOrDefault(request,
169                    CONTROL_AE_EXPOSURE_COMPENSATION,
170                    /*defaultValue*/0);
171
172            if (!compensationRange.contains(compensation)) {
173                Log.w(TAG,
174                        "convertRequestMetadata - control.aeExposureCompensation " +
175                        "is out of range, ignoring value");
176                compensation = 0;
177            }
178
179            params.setExposureCompensation(compensation);
180        }
181
182        // control.aeLock
183        {
184            Boolean aeLock = getIfSupported(request, CONTROL_AE_LOCK, /*defaultValue*/false,
185                    params.isAutoExposureLockSupported(),
186                    /*allowedValue*/false);
187
188            if (aeLock != null) {
189                params.setAutoExposureLock(aeLock);
190            }
191
192            if (VERBOSE) {
193                Log.v(TAG, "convertRequestToMetadata - control.aeLock set to " + aeLock);
194            }
195
196            // TODO: Don't add control.aeLock to availableRequestKeys if it's not supported
197        }
198
199        // control.aeMode, flash.mode
200        mapAeAndFlashMode(request, /*out*/params);
201
202        // control.afMode
203        {
204            int afMode = ParamsUtils.getOrDefault(request, CONTROL_AF_MODE,
205                    /*defaultValue*/CONTROL_AF_MODE_OFF);
206            String focusMode = LegacyMetadataMapper.convertAfModeToLegacy(afMode,
207                    params.getSupportedFocusModes());
208
209            if (focusMode != null) {
210                params.setFocusMode(focusMode);
211            }
212
213            if (VERBOSE) {
214                Log.v(TAG, "convertRequestToMetadata - control.afMode "
215                        + afMode + " mapped to " + focusMode);
216            }
217        }
218
219        // control.awbLock
220        {
221            Boolean awbLock = getIfSupported(request, CONTROL_AWB_LOCK, /*defaultValue*/false,
222                    params.isAutoWhiteBalanceLockSupported(),
223                    /*allowedValue*/false);
224
225            if (awbLock != null) {
226                params.setAutoWhiteBalanceLock(awbLock);
227            }
228
229         // TODO: Don't add control.awbLock to availableRequestKeys if it's not supported
230        }
231
232        // lens.focusDistance
233        {
234            boolean infinityFocusSupported =
235                    ListUtils.listContains(params.getSupportedFocusModes(),
236                            Parameters.FOCUS_MODE_INFINITY);
237            Float focusDistance = getIfSupported(request, LENS_FOCUS_DISTANCE,
238                    /*defaultValue*/0f, infinityFocusSupported, /*allowedValue*/0f);
239
240            if (focusDistance == null || focusDistance != 0f) {
241                Log.w(TAG,
242                        "convertRequestToMetadata - Ignoring android.lens.focusDistance "
243                                + infinityFocusSupported + ", only 0.0f is supported");
244            }
245        }
246
247        // control.sceneMode, control.mode
248        {
249            // TODO: Map FACE_PRIORITY scene mode to face detection.
250
251            if (params.getSupportedSceneModes() != null) {
252                int controlMode = ParamsUtils.getOrDefault(request, CONTROL_MODE,
253                    /*defaultValue*/CONTROL_MODE_AUTO);
254                String modeToSet;
255                switch (controlMode) {
256                    case CONTROL_MODE_USE_SCENE_MODE: {
257                        int sceneMode = ParamsUtils.getOrDefault(request, CONTROL_SCENE_MODE,
258                        /*defaultValue*/CONTROL_SCENE_MODE_DISABLED);
259                        String legacySceneMode = LegacyMetadataMapper.
260                                convertSceneModeToLegacy(sceneMode);
261                        if (legacySceneMode != null) {
262                            modeToSet = legacySceneMode;
263                        } else {
264                            modeToSet = Parameters.SCENE_MODE_AUTO;
265                            Log.w(TAG, "Skipping unknown requested scene mode: " + sceneMode);
266                        }
267                        break;
268                    }
269                    case CONTROL_MODE_AUTO: {
270                        modeToSet = Parameters.SCENE_MODE_AUTO;
271                        break;
272                    }
273                    default: {
274                        Log.w(TAG, "Control mode " + controlMode +
275                                " is unsupported, defaulting to AUTO");
276                        modeToSet = Parameters.SCENE_MODE_AUTO;
277                    }
278                }
279                params.setSceneMode(modeToSet);
280            }
281        }
282
283        // control.effectMode
284        {
285            if (params.getSupportedColorEffects() != null) {
286                int effectMode = ParamsUtils.getOrDefault(request, CONTROL_EFFECT_MODE,
287                    /*defaultValue*/CONTROL_EFFECT_MODE_OFF);
288                String legacyEffectMode = LegacyMetadataMapper.convertEffectModeToLegacy(effectMode);
289                if (legacyEffectMode != null) {
290                    params.setColorEffect(legacyEffectMode);
291                } else {
292                    params.setColorEffect(Parameters.EFFECT_NONE);
293                    Log.w(TAG, "Skipping unknown requested effect mode: " + effectMode);
294                }
295            }
296        }
297    }
298
299    private static List<Camera.Area> convertMeteringRegionsToLegacy(
300            Rect activeArray, ParameterUtils.ZoomData zoomData,
301            MeteringRectangle[] meteringRegions, int maxNumMeteringAreas, String regionName) {
302        if (meteringRegions == null || maxNumMeteringAreas <= 0) {
303            if (maxNumMeteringAreas > 0) {
304                return Arrays.asList(ParameterUtils.CAMERA_AREA_DEFAULT);
305            } else {
306                return null;
307            }
308        }
309
310        // Add all non-zero weight regions to the list
311        List<MeteringRectangle> meteringRectangleList = new ArrayList<>();
312        for (MeteringRectangle rect : meteringRegions) {
313            if (rect.getMeteringWeight() != MeteringRectangle.METERING_WEIGHT_DONT_CARE) {
314                meteringRectangleList.add(rect);
315            }
316        }
317
318        // Ignore any regions beyond our maximum supported count
319        int countMeteringAreas =
320                Math.min(maxNumMeteringAreas, meteringRectangleList.size());
321        List<Camera.Area> meteringAreaList = new ArrayList<>(countMeteringAreas);
322
323        for (int i = 0; i < countMeteringAreas; ++i) {
324            MeteringRectangle rect = meteringRectangleList.get(i);
325
326            ParameterUtils.MeteringData meteringData =
327                    ParameterUtils.convertMeteringRectangleToLegacy(activeArray, rect, zoomData);
328            meteringAreaList.add(meteringData.meteringArea);
329        }
330
331        if (maxNumMeteringAreas < meteringRectangleList.size()) {
332            Log.w(TAG,
333                    "convertMeteringRegionsToLegacy - Too many requested " + regionName +
334                            " regions, ignoring all beyond the first " + maxNumMeteringAreas);
335        }
336
337        if (VERBOSE) {
338            Log.v(TAG, "convertMeteringRegionsToLegacy - " + regionName + " areas = "
339                    + ParameterUtils.stringFromAreaList(meteringAreaList));
340        }
341
342        return meteringAreaList;
343    }
344
345    private static void mapAeAndFlashMode(CaptureRequest r, /*out*/Parameters p) {
346        int flashMode = ParamsUtils.getOrDefault(r, FLASH_MODE, FLASH_MODE_OFF);
347        int aeMode = ParamsUtils.getOrDefault(r, CONTROL_AE_MODE, CONTROL_AE_MODE_ON);
348
349        List<String> supportedFlashModes = p.getSupportedFlashModes();
350
351        String flashModeSetting = null;
352
353        // Flash is OFF by default, on cameras that support flash
354        if (ListUtils.listContains(supportedFlashModes, Parameters.FLASH_MODE_OFF)) {
355            flashModeSetting = Parameters.FLASH_MODE_OFF;
356        }
357
358        /*
359         * Map all of the control.aeMode* enums, but ignore AE_MODE_OFF since we never support it
360         */
361
362        // Ignore flash.mode controls unless aeMode == ON
363        if (aeMode == CONTROL_AE_MODE_ON) {
364            if (flashMode == FLASH_MODE_TORCH) {
365                    if (ListUtils.listContains(supportedFlashModes, Parameters.FLASH_MODE_TORCH)) {
366                        flashModeSetting = Parameters.FLASH_MODE_TORCH;
367                    } else {
368                        Log.w(TAG, "mapAeAndFlashMode - Ignore flash.mode == TORCH;" +
369                                "camera does not support it");
370                    }
371            } else if (flashMode == FLASH_MODE_SINGLE) {
372                if (ListUtils.listContains(supportedFlashModes, Parameters.FLASH_MODE_ON)) {
373                    flashModeSetting = Parameters.FLASH_MODE_ON;
374                } else {
375                    Log.w(TAG, "mapAeAndFlashMode - Ignore flash.mode == SINGLE;" +
376                            "camera does not support it");
377                }
378            } else {
379                // Use the default FLASH_MODE_OFF
380            }
381        } else if (aeMode == CONTROL_AE_MODE_ON_ALWAYS_FLASH) {
382                if (ListUtils.listContains(supportedFlashModes, Parameters.FLASH_MODE_ON)) {
383                    flashModeSetting = Parameters.FLASH_MODE_ON;
384                } else {
385                    Log.w(TAG, "mapAeAndFlashMode - Ignore control.aeMode == ON_ALWAYS_FLASH;" +
386                            "camera does not support it");
387                }
388        } else if (aeMode == CONTROL_AE_MODE_ON_AUTO_FLASH) {
389            if (ListUtils.listContains(supportedFlashModes, Parameters.FLASH_MODE_AUTO)) {
390                flashModeSetting = Parameters.FLASH_MODE_AUTO;
391            } else {
392                Log.w(TAG, "mapAeAndFlashMode - Ignore control.aeMode == ON_AUTO_FLASH;" +
393                        "camera does not support it");
394            }
395        } else if (aeMode == CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE) {
396                if (ListUtils.listContains(supportedFlashModes, Parameters.FLASH_MODE_RED_EYE)) {
397                    flashModeSetting = Parameters.FLASH_MODE_RED_EYE;
398                } else {
399                    Log.w(TAG, "mapAeAndFlashMode - Ignore control.aeMode == ON_AUTO_FLASH_REDEYE;"
400                            + "camera does not support it");
401                }
402        } else {
403            // Default to aeMode == ON, flash = OFF
404        }
405
406        if (flashModeSetting != null) {
407            p.setFlashMode(flashModeSetting);
408        }
409
410        if (VERBOSE) {
411                Log.v(TAG,
412                        "mapAeAndFlashMode - set flash.mode (api1) to " + flashModeSetting
413                        + ", requested (api2) " + flashMode
414                        + ", supported (api1) " + ListUtils.listToString(supportedFlashModes));
415        }
416    }
417
418    /**
419     * Returns null if the anti-banding mode enum is not supported.
420     */
421    private static String convertAeAntiBandingModeToLegacy(int mode) {
422        switch (mode) {
423            case CONTROL_AE_ANTIBANDING_MODE_OFF: {
424                return Parameters.ANTIBANDING_OFF;
425            }
426            case CONTROL_AE_ANTIBANDING_MODE_50HZ: {
427                return Parameters.ANTIBANDING_50HZ;
428            }
429            case CONTROL_AE_ANTIBANDING_MODE_60HZ: {
430                return Parameters.ANTIBANDING_60HZ;
431            }
432            case CONTROL_AE_ANTIBANDING_MODE_AUTO: {
433                return Parameters.ANTIBANDING_AUTO;
434            }
435            default: {
436                return null;
437            }
438        }
439    }
440
441    private static int[] convertAeFpsRangeToLegacy(Range<Integer> fpsRange) {
442        int[] legacyFps = new int[2];
443        legacyFps[Parameters.PREVIEW_FPS_MIN_INDEX] = fpsRange.getLower();
444        legacyFps[Parameters.PREVIEW_FPS_MAX_INDEX] = fpsRange.getUpper();
445        return legacyFps;
446    }
447
448    /**
449     * Return {@code null} if the value is not supported, otherwise return the retrieved key's
450     * value from the request (or the default value if it wasn't set).
451     *
452     * <p>If the fetched value in the request is equivalent to {@code allowedValue},
453     * then omit the warning (e.g. turning off AF lock on a camera
454     * that always has the AF lock turned off is a silent no-op), but still return {@code null}.</p>
455     *
456     * <p>Logs a warning to logcat if the key is not supported by api1 camera device.</p.
457     */
458    private static <T> T getIfSupported(
459            CaptureRequest r, CaptureRequest.Key<T> key, T defaultValue, boolean isSupported,
460            T allowedValue) {
461        T val = ParamsUtils.getOrDefault(r, key, defaultValue);
462
463        if (!isSupported) {
464            if (!Objects.equals(val, allowedValue)) {
465                Log.w(TAG, key.getName() + " is not supported; ignoring requested value " + val);
466            }
467            return null;
468        }
469
470        return val;
471    }
472}
473