CameraSettings.java revision 10208b3b4e2e9ca5af27be49356288531e3cd45b
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    private static final String TAG = "CameraSettings";
75
76    private final Context mContext;
77    private final Parameters mParameters;
78    private final CameraInfo[] mCameraInfo;
79    private final int mCameraId;
80
81    public CameraSettings(Activity activity, Parameters parameters,
82                          int cameraId, CameraInfo[] cameraInfo) {
83        mContext = activity;
84        mParameters = parameters;
85        mCameraId = cameraId;
86        mCameraInfo = cameraInfo;
87    }
88
89    public PreferenceGroup getPreferenceGroup(int preferenceRes) {
90        PreferenceInflater inflater = new PreferenceInflater(mContext);
91        PreferenceGroup group =
92                (PreferenceGroup) inflater.inflate(preferenceRes);
93        initPreference(group);
94        return group;
95    }
96
97    public static void initialCameraPictureSize(
98            Context context, Parameters parameters) {
99        // When launching the camera app first time, we will set the picture
100        // size to the first one in the list defined in "arrays.xml" and is also
101        // supported by the driver.
102        List<Size> supported = parameters.getSupportedPictureSizes();
103        if (supported == null) return;
104        for (String candidate : context.getResources().getStringArray(
105                R.array.pref_camera_picturesize_entryvalues)) {
106            if (setCameraPictureSize(candidate, supported, parameters)) {
107                SharedPreferences.Editor editor = ComboPreferences
108                        .get(context).edit();
109                editor.putString(KEY_PICTURE_SIZE, candidate);
110                editor.apply();
111                return;
112            }
113        }
114        Log.e(TAG, "No supported picture size found");
115    }
116
117    public static void removePreferenceFromScreen(
118            PreferenceGroup group, String key) {
119        removePreference(group, key);
120    }
121
122    public static boolean setCameraPictureSize(
123            String candidate, List<Size> supported, Parameters parameters) {
124        int index = candidate.indexOf('x');
125        if (index == NOT_FOUND) return false;
126        int width = Integer.parseInt(candidate.substring(0, index));
127        int height = Integer.parseInt(candidate.substring(index + 1));
128        for (Size size: supported) {
129            if (size.width == width && size.height == height) {
130                parameters.setPictureSize(width, height);
131                return true;
132            }
133        }
134        return false;
135    }
136
137    private void initPreference(PreferenceGroup group) {
138        ListPreference videoQuality = group.findPreference(KEY_VIDEO_QUALITY);
139        ListPreference videoTimeLapseQuality = group.findPreference(KEY_VIDEO_TIME_LAPSE_QUALITY);
140        ListPreference pictureSize = group.findPreference(KEY_PICTURE_SIZE);
141        ListPreference whiteBalance =  group.findPreference(KEY_WHITE_BALANCE);
142        ListPreference colorEffect = group.findPreference(KEY_COLOR_EFFECT);
143        ListPreference sceneMode = group.findPreference(KEY_SCENE_MODE);
144        ListPreference flashMode = group.findPreference(KEY_FLASH_MODE);
145        ListPreference focusMode = group.findPreference(KEY_FOCUS_MODE);
146        ListPreference exposure = group.findPreference(KEY_EXPOSURE);
147        IconListPreference cameraIdPref =
148                (IconListPreference)group.findPreference(KEY_CAMERA_ID);
149        ListPreference videoFlashMode =
150                group.findPreference(KEY_VIDEOCAMERA_FLASH_MODE);
151
152        // Since the screen could be loaded from different resources, we need
153        // to check if the preference is available here
154        if (videoQuality != null) {
155            initVideoQuality(videoQuality);
156        }
157
158        // Filter out unsupported settings / options
159        if (videoTimeLapseQuality != null) {
160            filterUnsupportedOptions(group, videoTimeLapseQuality,
161                    getSupportedTimeLapseProfiles(mCameraId));
162        }
163        if (pictureSize != null) {
164            filterUnsupportedOptions(group, pictureSize, sizeListToStringList(
165                    mParameters.getSupportedPictureSizes()));
166        }
167        if (whiteBalance != null) {
168            filterUnsupportedOptions(group,
169                    whiteBalance, mParameters.getSupportedWhiteBalance());
170        }
171        if (colorEffect != null) {
172            filterUnsupportedOptions(group,
173                    colorEffect, mParameters.getSupportedColorEffects());
174        }
175        if (sceneMode != null) {
176            filterUnsupportedOptions(group,
177                    sceneMode, mParameters.getSupportedSceneModes());
178        }
179        if (flashMode != null) {
180            filterUnsupportedOptions(group,
181                    flashMode, mParameters.getSupportedFlashModes());
182        }
183        if (focusMode != null) {
184            filterUnsupportedOptions(group,
185                    focusMode, mParameters.getSupportedFocusModes());
186        }
187        if (videoFlashMode != null) {
188            filterUnsupportedOptions(group,
189                    videoFlashMode, mParameters.getSupportedFlashModes());
190        }
191        if (exposure != null) buildExposureCompensation(group, exposure);
192        if (cameraIdPref != null) buildCameraId(group, cameraIdPref);
193    }
194
195    private static List<String> getSupportedTimeLapseProfiles(int cameraId) {
196        ArrayList<String> supportedProfiles = new ArrayList<String>();
197        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_480P)) {
198            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_480P));
199        }
200        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_720P)) {
201            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_720P));
202        }
203        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_1080P)) {
204            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_1080P));
205        }
206
207        return supportedProfiles;
208    }
209
210    private void buildExposureCompensation(
211            PreferenceGroup group, ListPreference exposure) {
212        int max = mParameters.getMaxExposureCompensation();
213        int min = mParameters.getMinExposureCompensation();
214        if (max == 0 && min == 0) {
215            removePreference(group, exposure.getKey());
216            return;
217        }
218        float step = mParameters.getExposureCompensationStep();
219
220        // show only integer values for exposure compensation
221        int maxValue = (int) Math.floor(max * step);
222        int minValue = (int) Math.ceil(min * step);
223        CharSequence entries[] = new CharSequence[maxValue - minValue + 1];
224        CharSequence entryValues[] = new CharSequence[maxValue - minValue + 1];
225        for (int i = minValue; i <= maxValue; ++i) {
226            entryValues[maxValue - i] = Integer.toString(Math.round(i / step));
227            StringBuilder builder = new StringBuilder();
228            if (i > 0) builder.append('+');
229            entries[maxValue - i] = builder.append(i).toString();
230        }
231        exposure.setEntries(entries);
232        exposure.setEntryValues(entryValues);
233    }
234
235    private void buildCameraId(
236            PreferenceGroup group, IconListPreference preference) {
237        int numOfCameras = mCameraInfo.length;
238        if (numOfCameras < 2) {
239            removePreference(group, preference.getKey());
240            return;
241        }
242
243        CharSequence[] entryValues = new CharSequence[2];
244        for (int i = 0 ; i < mCameraInfo.length ; ++i) {
245            int index =
246                    (mCameraInfo[i].facing == CameraInfo.CAMERA_FACING_FRONT)
247                    ? CameraInfo.CAMERA_FACING_FRONT
248                    : CameraInfo.CAMERA_FACING_BACK;
249            if (entryValues[index] == null) {
250                entryValues[index] = "" + i;
251                if (entryValues[((index == 1) ? 0 : 1)] != null) break;
252            }
253        }
254        preference.setEntryValues(entryValues);
255    }
256
257    private static boolean removePreference(PreferenceGroup group, String key) {
258        for (int i = 0, n = group.size(); i < n; i++) {
259            CameraPreference child = group.get(i);
260            if (child instanceof PreferenceGroup) {
261                if (removePreference((PreferenceGroup) child, key)) {
262                    return true;
263                }
264            }
265            if (child instanceof ListPreference &&
266                    ((ListPreference) child).getKey().equals(key)) {
267                group.removePreference(i);
268                return true;
269            }
270        }
271        return false;
272    }
273
274    private void filterUnsupportedOptions(PreferenceGroup group,
275            ListPreference pref, List<String> supported) {
276
277        // Remove the preference if the parameter is not supported or there is
278        // only one options for the settings.
279        if (supported == null || supported.size() <= 1) {
280            removePreference(group, pref.getKey());
281            return;
282        }
283
284        pref.filterUnsupported(supported);
285        if (pref.getEntries().length <= 1) {
286            removePreference(group, pref.getKey());
287            return;
288        }
289
290        // Set the value to the first entry if it is invalid.
291        String value = pref.getValue();
292        if (pref.findIndexOfValue(value) == NOT_FOUND) {
293            pref.setValueIndex(0);
294        }
295    }
296
297    private static List<String> sizeListToStringList(List<Size> sizes) {
298        ArrayList<String> list = new ArrayList<String>();
299        for (Size size : sizes) {
300            list.add(String.format("%dx%d", size.width, size.height));
301        }
302        return list;
303    }
304
305    public static void upgradeLocalPreferences(SharedPreferences pref) {
306        int version;
307        try {
308            version = pref.getInt(KEY_LOCAL_VERSION, 0);
309        } catch (Exception ex) {
310            version = 0;
311        }
312        if (version == CURRENT_LOCAL_VERSION) return;
313        SharedPreferences.Editor editor = pref.edit();
314        editor.putInt(KEY_LOCAL_VERSION, CURRENT_LOCAL_VERSION);
315        editor.apply();
316    }
317
318    public static void upgradeGlobalPreferences(SharedPreferences pref) {
319        int version;
320        try {
321            version = pref.getInt(KEY_VERSION, 0);
322        } catch (Exception ex) {
323            version = 0;
324        }
325        if (version == CURRENT_VERSION) return;
326
327        SharedPreferences.Editor editor = pref.edit();
328        if (version == 0) {
329            // We won't use the preference which change in version 1.
330            // So, just upgrade to version 1 directly
331            version = 1;
332        }
333        if (version == 1) {
334            // Change jpeg quality {65,75,85} to {normal,fine,superfine}
335            String quality = pref.getString(KEY_JPEG_QUALITY, "85");
336            if (quality.equals("65")) {
337                quality = "normal";
338            } else if (quality.equals("75")) {
339                quality = "fine";
340            } else {
341                quality = "superfine";
342            }
343            editor.putString(KEY_JPEG_QUALITY, quality);
344            version = 2;
345        }
346        if (version == 2) {
347            editor.putString(KEY_RECORD_LOCATION,
348                    pref.getBoolean(KEY_RECORD_LOCATION, false)
349                    ? RecordLocationPreference.VALUE_ON
350                    : RecordLocationPreference.VALUE_NONE);
351            version = 3;
352        }
353        if (version == 3) {
354            // Just use video quality to replace it and
355            // ignore the current settings.
356            editor.remove("pref_camera_videoquality_key");
357            editor.remove("pref_camera_video_duration_key");
358        }
359        editor.putInt(KEY_VERSION, CURRENT_VERSION);
360        editor.apply();
361    }
362
363    public static boolean getVideoQuality(String quality) {
364        return VIDEO_QUALITY_YOUTUBE.equals(
365                quality) || VIDEO_QUALITY_HIGH.equals(quality);
366    }
367
368    public static int getVidoeDurationInMillis(String quality) {
369        if (VIDEO_QUALITY_MMS.equals(quality)) {
370            return MMS_VIDEO_DURATION * 1000;
371        } else if (VIDEO_QUALITY_YOUTUBE.equals(quality)) {
372            return YOUTUBE_VIDEO_DURATION * 1000;
373        }
374        return DEFAULT_VIDEO_DURATION * 1000;
375    }
376
377    public static int readPreferredCameraId(SharedPreferences pref) {
378        return Integer.parseInt(pref.getString(KEY_CAMERA_ID, "0"));
379    }
380
381    public static void writePreferredCameraId(SharedPreferences pref,
382            int cameraId) {
383        Editor editor = pref.edit();
384        editor.putString(KEY_CAMERA_ID, Integer.toString(cameraId));
385        editor.apply();
386    }
387
388
389    public static void restorePreferences(Context context,
390            ComboPreferences preferences, Parameters parameters) {
391        int currentCameraId = readPreferredCameraId(preferences);
392
393        // Clear the preferences of both cameras.
394        int backCameraId = CameraHolder.instance().getBackCameraId();
395        if (backCameraId != -1) {
396            preferences.setLocalId(context, backCameraId);
397            Editor editor = preferences.edit();
398            editor.clear();
399            editor.apply();
400        }
401        int frontCameraId = CameraHolder.instance().getFrontCameraId();
402        if (frontCameraId != -1) {
403            preferences.setLocalId(context, frontCameraId);
404            Editor editor = preferences.edit();
405            editor.clear();
406            editor.apply();
407        }
408
409        upgradeGlobalPreferences(preferences.getGlobal());
410        upgradeLocalPreferences(preferences.getLocal());
411
412        // Write back the current camera id because parameters are related to
413        // the camera. Otherwise, we may switch to the front camera but the
414        // initial picture size is that of the back camera.
415        initialCameraPictureSize(context, parameters);
416        writePreferredCameraId(preferences, currentCameraId);
417    }
418
419    private void initVideoQuality(ListPreference videoQuality) {
420        CharSequence[] entries = videoQuality.getEntries();
421        CharSequence[] values = videoQuality.getEntryValues();
422        if (Util.isMmsCapable(mContext)) {
423            // We need to fill in the device-dependent value (in seconds).
424            for (int i = 0; i < entries.length; ++i) {
425                if (VIDEO_QUALITY_MMS.equals(values[i])) {
426                    entries[i] = entries[i].toString().replace(
427                            "30", Integer.toString(MMS_VIDEO_DURATION));
428                    break;
429                }
430            }
431        } else {
432            // The device does not support mms. Remove it. Using
433            // filterUnsupported is not efficient but adding a new method
434            // for remove is not worth it.
435            ArrayList<String> supported = new ArrayList<String>();
436            for (int i = 0; i < entries.length; ++i) {
437                if (!VIDEO_QUALITY_MMS.equals(values[i])) {
438                    supported.add(values[i].toString());
439                }
440            }
441            videoQuality.filterUnsupported(supported);
442        }
443    }
444}
445