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