CameraSettings.java revision f59f7fb9870c1f285f9bdb5e3ca47a1548527837
1/*
2 * Copyright (C) 2009 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 com.android.camera;
18
19import android.app.Activity;
20import android.content.Context;
21import android.content.SharedPreferences;
22import android.content.SharedPreferences.Editor;
23import android.hardware.Camera.CameraInfo;
24import android.hardware.Camera.Parameters;
25import android.hardware.Camera.Size;
26import android.media.CamcorderProfile;
27import android.util.Log;
28
29import java.util.ArrayList;
30import java.util.List;
31
32/**
33 *  Provides utilities and keys for Camera settings.
34 */
35public class CameraSettings {
36    private static final int NOT_FOUND = -1;
37
38    public static final String KEY_VERSION = "pref_version_key";
39    public static final String KEY_LOCAL_VERSION = "pref_local_version_key";
40    public static final String KEY_RECORD_LOCATION = RecordLocationPreference.KEY;
41    public static final String KEY_VIDEO_QUALITY = "pref_video_quality_key";
42    public static final String KEY_VIDEO_TIME_LAPSE_QUALITY = "pref_video_time_lapse_quality_key";
43    public static final String KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL = "pref_video_time_lapse_frame_interval_key";
44    public static final String KEY_PICTURE_SIZE = "pref_camera_picturesize_key";
45    public static final String KEY_JPEG_QUALITY = "pref_camera_jpegquality_key";
46    public static final String KEY_FOCUS_MODE = "pref_camera_focusmode_key";
47    public static final String KEY_FLASH_MODE = "pref_camera_flashmode_key";
48    public static final String KEY_VIDEOCAMERA_FLASH_MODE = "pref_camera_video_flashmode_key";
49    public static final String KEY_COLOR_EFFECT = "pref_camera_coloreffect_key";
50    public static final String KEY_WHITE_BALANCE = "pref_camera_whitebalance_key";
51    public static final String KEY_SCENE_MODE = "pref_camera_scenemode_key";
52    public static final String KEY_EXPOSURE = "pref_camera_exposure_key";
53    public static final String KEY_CAMERA_ID = "pref_camera_id_key";
54
55    private static final String VIDEO_QUALITY_HIGH = "high";
56    private static final String VIDEO_QUALITY_MMS = "mms";
57    private static final String VIDEO_QUALITY_YOUTUBE = "youtube";
58
59    public static final String EXPOSURE_DEFAULT_VALUE = "0";
60
61    public static final int CURRENT_VERSION = 4;
62    public static final int CURRENT_LOCAL_VERSION = 1;
63
64    // max video duration in seconds for mms and youtube.
65    private static final int MMS_VIDEO_DURATION = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW).duration;
66    private static final int YOUTUBE_VIDEO_DURATION = 10 * 60; // 10 mins
67    private static final int DEFAULT_VIDEO_DURATION = 30 * 60; // 10 mins
68
69    public static final String DEFAULT_VIDEO_QUALITY_VALUE = "high";
70
71    // MMS video length
72    public static final int DEFAULT_VIDEO_DURATION_VALUE = -1;
73
74    @SuppressWarnings("unused")
75    private static final String TAG = "CameraSettings";
76
77    private final Context mContext;
78    private final Parameters mParameters;
79    private final CameraInfo[] mCameraInfo;
80    private final int mCameraId;
81
82    public CameraSettings(Activity activity, Parameters parameters,
83                          int cameraId, CameraInfo[] cameraInfo) {
84        mContext = activity;
85        mParameters = parameters;
86        mCameraId = cameraId;
87        mCameraInfo = cameraInfo;
88    }
89
90    public PreferenceGroup getPreferenceGroup(int preferenceRes) {
91        PreferenceInflater inflater = new PreferenceInflater(mContext);
92        PreferenceGroup group =
93                (PreferenceGroup) inflater.inflate(preferenceRes);
94        initPreference(group);
95        return group;
96    }
97
98    public static void initialCameraPictureSize(
99            Context context, Parameters parameters) {
100        // When launching the camera app first time, we will set the picture
101        // size to the first one in the list defined in "arrays.xml" and is also
102        // supported by the driver.
103        List<Size> supported = parameters.getSupportedPictureSizes();
104        if (supported == null) return;
105        for (String candidate : context.getResources().getStringArray(
106                R.array.pref_camera_picturesize_entryvalues)) {
107            if (setCameraPictureSize(candidate, supported, parameters)) {
108                SharedPreferences.Editor editor = ComboPreferences
109                        .get(context).edit();
110                editor.putString(KEY_PICTURE_SIZE, candidate);
111                editor.apply();
112                return;
113            }
114        }
115        Log.e(TAG, "No supported picture size found");
116    }
117
118    public static void removePreferenceFromScreen(
119            PreferenceGroup group, String key) {
120        removePreference(group, key);
121    }
122
123    public static boolean setCameraPictureSize(
124            String candidate, List<Size> supported, Parameters parameters) {
125        int index = candidate.indexOf('x');
126        if (index == NOT_FOUND) return false;
127        int width = Integer.parseInt(candidate.substring(0, index));
128        int height = Integer.parseInt(candidate.substring(index + 1));
129        for (Size size: supported) {
130            if (size.width == width && size.height == height) {
131                parameters.setPictureSize(width, height);
132                return true;
133            }
134        }
135        return false;
136    }
137
138    private void initPreference(PreferenceGroup group) {
139        ListPreference videoQuality = group.findPreference(KEY_VIDEO_QUALITY);
140        ListPreference videoTimeLapseQuality = group.findPreference(KEY_VIDEO_TIME_LAPSE_QUALITY);
141        ListPreference pictureSize = group.findPreference(KEY_PICTURE_SIZE);
142        ListPreference whiteBalance =  group.findPreference(KEY_WHITE_BALANCE);
143        ListPreference colorEffect = group.findPreference(KEY_COLOR_EFFECT);
144        ListPreference sceneMode = group.findPreference(KEY_SCENE_MODE);
145        ListPreference flashMode = group.findPreference(KEY_FLASH_MODE);
146        ListPreference focusMode = group.findPreference(KEY_FOCUS_MODE);
147        ListPreference exposure = group.findPreference(KEY_EXPOSURE);
148        IconListPreference cameraIdPref =
149                (IconListPreference)group.findPreference(KEY_CAMERA_ID);
150        ListPreference videoFlashMode =
151                group.findPreference(KEY_VIDEOCAMERA_FLASH_MODE);
152
153        // Since the screen could be loaded from different resources, we need
154        // to check if the preference is available here
155        if (videoQuality != null) {
156            // Modify video duration settings.
157            // The first entry is for MMS video duration, and we need to fill
158            // in the device-dependent value (in seconds).
159            CharSequence[] entries = videoQuality.getEntries();
160            CharSequence[] values = videoQuality.getEntryValues();
161            for (int i = 0; i < entries.length; ++i) {
162                if (VIDEO_QUALITY_MMS.equals(values[i])) {
163                    entries[i] = entries[i].toString().replace(
164                            "30", Integer.toString(MMS_VIDEO_DURATION));
165                    break;
166                }
167            }
168        }
169
170        // Filter out unsupported settings / options
171        if (videoTimeLapseQuality != null) {
172            filterUnsupportedOptions(group, videoTimeLapseQuality,
173                    getSupportedTimeLapseProfiles(mCameraId));
174        }
175        if (pictureSize != null) {
176            filterUnsupportedOptions(group, pictureSize, sizeListToStringList(
177                    mParameters.getSupportedPictureSizes()));
178        }
179        if (whiteBalance != null) {
180            filterUnsupportedOptions(group,
181                    whiteBalance, mParameters.getSupportedWhiteBalance());
182        }
183        if (colorEffect != null) {
184            filterUnsupportedOptions(group,
185                    colorEffect, mParameters.getSupportedColorEffects());
186        }
187        if (sceneMode != null) {
188            filterUnsupportedOptions(group,
189                    sceneMode, mParameters.getSupportedSceneModes());
190        }
191        if (flashMode != null) {
192            filterUnsupportedOptions(group,
193                    flashMode, mParameters.getSupportedFlashModes());
194        }
195        if (focusMode != null) {
196            filterUnsupportedOptions(group,
197                    focusMode, mParameters.getSupportedFocusModes());
198        }
199        if (videoFlashMode != null) {
200            filterUnsupportedOptions(group,
201                    videoFlashMode, mParameters.getSupportedFlashModes());
202        }
203        if (exposure != null) buildExposureCompensation(group, exposure);
204        if (cameraIdPref != null) buildCameraId(group, cameraIdPref);
205    }
206
207    private static List<String> getSupportedTimeLapseProfiles(int cameraId) {
208        ArrayList<String> supportedProfiles = new ArrayList<String>();
209        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_480P)) {
210            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_480P));
211        }
212        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_720P)) {
213            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_720P));
214        }
215        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_1080P)) {
216            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_1080P));
217        }
218
219        return supportedProfiles;
220    }
221
222    private void buildExposureCompensation(
223            PreferenceGroup group, ListPreference exposure) {
224        int max = mParameters.getMaxExposureCompensation();
225        int min = mParameters.getMinExposureCompensation();
226        if (max == 0 && min == 0) {
227            removePreference(group, exposure.getKey());
228            return;
229        }
230        float step = mParameters.getExposureCompensationStep();
231
232        // show only integer values for exposure compensation
233        int maxValue = (int) Math.floor(max * step);
234        int minValue = (int) Math.ceil(min * step);
235        CharSequence entries[] = new CharSequence[maxValue - minValue + 1];
236        CharSequence entryValues[] = new CharSequence[maxValue - minValue + 1];
237        for (int i = minValue; i <= maxValue; ++i) {
238            entryValues[maxValue - i] = Integer.toString(Math.round(i / step));
239            StringBuilder builder = new StringBuilder();
240            if (i > 0) builder.append('+');
241            entries[maxValue - i] = builder.append(i).toString();
242        }
243        exposure.setEntries(entries);
244        exposure.setEntryValues(entryValues);
245    }
246
247    private void buildCameraId(
248            PreferenceGroup group, IconListPreference cameraId) {
249        int numOfCameras = mCameraInfo.length;
250        if (numOfCameras < 2) {
251            removePreference(group, cameraId.getKey());
252            return;
253        }
254
255        CharSequence entries[] = new CharSequence[numOfCameras];
256        CharSequence entryValues[] = new CharSequence[numOfCameras];
257        int[] iconIds = new int[numOfCameras];
258        int[] largeIconIds = new int[numOfCameras];
259        for (int i = 0; i < numOfCameras; i++) {
260            entryValues[i] = Integer.toString(i);
261            if (mCameraInfo[i].facing == CameraInfo.CAMERA_FACING_FRONT) {
262                entries[i] = mContext.getString(
263                        R.string.pref_camera_id_entry_front);
264                iconIds[i] = R.drawable.ic_menuselect_camera_facing_front;
265                largeIconIds[i] = R.drawable.ic_viewfinder_camera_facing_front;
266            } else {
267                entries[i] = mContext.getString(
268                        R.string.pref_camera_id_entry_back);
269                iconIds[i] = R.drawable.ic_menuselect_camera_facing_back;
270                largeIconIds[i] = R.drawable.ic_viewfinder_camera_facing_back;
271            }
272        }
273        cameraId.setEntries(entries);
274        cameraId.setEntryValues(entryValues);
275        cameraId.setIconIds(iconIds);
276        cameraId.setLargeIconIds(largeIconIds);
277    }
278
279    private static boolean removePreference(PreferenceGroup group, String key) {
280        for (int i = 0, n = group.size(); i < n; i++) {
281            CameraPreference child = group.get(i);
282            if (child instanceof PreferenceGroup) {
283                if (removePreference((PreferenceGroup) child, key)) {
284                    return true;
285                }
286            }
287            if (child instanceof ListPreference &&
288                    ((ListPreference) child).getKey().equals(key)) {
289                group.removePreference(i);
290                return true;
291            }
292        }
293        return false;
294    }
295
296    private void filterUnsupportedOptions(PreferenceGroup group,
297            ListPreference pref, List<String> supported) {
298
299        CharSequence[] allEntries = pref.getEntries();
300
301        // Remove the preference if the parameter is not supported or there is
302        // only one options for the settings.
303        if (supported == null || supported.size() <= 1) {
304            removePreference(group, pref.getKey());
305            return;
306        }
307
308        pref.filterUnsupported(supported);
309        if (pref.getEntries().length <= 1) {
310            removePreference(group, pref.getKey());
311            return;
312        }
313
314        // Set the value to the first entry if it is invalid.
315        String value = pref.getValue();
316        if (pref.findIndexOfValue(value) == NOT_FOUND) {
317            pref.setValueIndex(0);
318        }
319    }
320
321    private static List<String> sizeListToStringList(List<Size> sizes) {
322        ArrayList<String> list = new ArrayList<String>();
323        for (Size size : sizes) {
324            list.add(String.format("%dx%d", size.width, size.height));
325        }
326        return list;
327    }
328
329    public static void upgradeLocalPreferences(SharedPreferences pref) {
330        int version;
331        try {
332            version = pref.getInt(KEY_LOCAL_VERSION, 0);
333        } catch (Exception ex) {
334            version = 0;
335        }
336        if (version == CURRENT_LOCAL_VERSION) return;
337        SharedPreferences.Editor editor = pref.edit();
338        editor.putInt(KEY_LOCAL_VERSION, CURRENT_LOCAL_VERSION);
339        editor.apply();
340    }
341
342    public static void upgradeGlobalPreferences(SharedPreferences pref) {
343        int version;
344        try {
345            version = pref.getInt(KEY_VERSION, 0);
346        } catch (Exception ex) {
347            version = 0;
348        }
349        if (version == CURRENT_VERSION) return;
350
351        SharedPreferences.Editor editor = pref.edit();
352        if (version == 0) {
353            // We won't use the preference which change in version 1.
354            // So, just upgrade to version 1 directly
355            version = 1;
356        }
357        if (version == 1) {
358            // Change jpeg quality {65,75,85} to {normal,fine,superfine}
359            String quality = pref.getString(KEY_JPEG_QUALITY, "85");
360            if (quality.equals("65")) {
361                quality = "normal";
362            } else if (quality.equals("75")) {
363                quality = "fine";
364            } else {
365                quality = "superfine";
366            }
367            editor.putString(KEY_JPEG_QUALITY, quality);
368            version = 2;
369        }
370        if (version == 2) {
371            editor.putString(KEY_RECORD_LOCATION,
372                    pref.getBoolean(KEY_RECORD_LOCATION, false)
373                    ? RecordLocationPreference.VALUE_ON
374                    : RecordLocationPreference.VALUE_NONE);
375            version = 3;
376        }
377        if (version == 3) {
378            // Just use video quality to replace it and
379            // ignore the current settings.
380            editor.remove("pref_camera_videoquality_key");
381            editor.remove("pref_camera_video_duration_key");
382        }
383        editor.putInt(KEY_VERSION, CURRENT_VERSION);
384        editor.apply();
385    }
386
387    public static void upgradeAllPreferences(ComboPreferences pref) {
388        upgradeGlobalPreferences(pref.getGlobal());
389        upgradeLocalPreferences(pref.getLocal());
390    }
391
392    public static boolean getVideoQuality(String quality) {
393        return VIDEO_QUALITY_YOUTUBE.equals(
394                quality) || VIDEO_QUALITY_HIGH.equals(quality);
395    }
396
397    public static int getVidoeDurationInMillis(String quality) {
398        if (VIDEO_QUALITY_MMS.equals(quality)) {
399            return MMS_VIDEO_DURATION * 1000;
400        } else if (VIDEO_QUALITY_YOUTUBE.equals(quality)) {
401            return YOUTUBE_VIDEO_DURATION * 1000;
402        }
403        return DEFAULT_VIDEO_DURATION * 1000;
404    }
405
406    public static int readPreferredCameraId(SharedPreferences pref) {
407        return Integer.parseInt(pref.getString(KEY_CAMERA_ID, "0"));
408    }
409
410    public static void writePreferredCameraId(SharedPreferences pref,
411            int cameraId) {
412        Editor editor = pref.edit();
413        editor.putString(KEY_CAMERA_ID, Integer.toString(cameraId));
414        editor.apply();
415    }
416}
417