CameraSettings.java revision 75da345f6899b6e10274b9a443b32848aa34f39c
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    public static final String EXPOSURE_DEFAULT_VALUE = "0";
56
57    public static final int CURRENT_VERSION = 4;
58    public static final int CURRENT_LOCAL_VERSION = 1;
59
60    // max video duration in seconds for mms and youtube.
61    private static final int MMS_VIDEO_DURATION = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW).duration;
62    private static final int YOUTUBE_VIDEO_DURATION = 15 * 60; // 15 mins
63    private static final int DEFAULT_VIDEO_DURATION = 0; // no limit
64
65    public static final String DEFAULT_VIDEO_QUALITY_VALUE = "high";
66
67    private static final String TAG = "CameraSettings";
68
69    private final Context mContext;
70    private final Parameters mParameters;
71    private final CameraInfo[] mCameraInfo;
72    private final int mCameraId;
73
74    public CameraSettings(Activity activity, Parameters parameters,
75                          int cameraId, CameraInfo[] cameraInfo) {
76        mContext = activity;
77        mParameters = parameters;
78        mCameraId = cameraId;
79        mCameraInfo = cameraInfo;
80    }
81
82    public PreferenceGroup getPreferenceGroup(int preferenceRes) {
83        PreferenceInflater inflater = new PreferenceInflater(mContext);
84        PreferenceGroup group =
85                (PreferenceGroup) inflater.inflate(preferenceRes);
86        initPreference(group);
87        return group;
88    }
89
90    public static void initialCameraPictureSize(
91            Context context, Parameters parameters) {
92        // When launching the camera app first time, we will set the picture
93        // size to the first one in the list defined in "arrays.xml" and is also
94        // supported by the driver.
95        List<Size> supported = parameters.getSupportedPictureSizes();
96        if (supported == null) return;
97        for (String candidate : context.getResources().getStringArray(
98                R.array.pref_camera_picturesize_entryvalues)) {
99            if (setCameraPictureSize(candidate, supported, parameters)) {
100                SharedPreferences.Editor editor = ComboPreferences
101                        .get(context).edit();
102                editor.putString(KEY_PICTURE_SIZE, candidate);
103                editor.apply();
104                return;
105            }
106        }
107        Log.e(TAG, "No supported picture size found");
108    }
109
110    public static void removePreferenceFromScreen(
111            PreferenceGroup group, String key) {
112        removePreference(group, key);
113    }
114
115    public static boolean setCameraPictureSize(
116            String candidate, List<Size> supported, Parameters parameters) {
117        int index = candidate.indexOf('x');
118        if (index == NOT_FOUND) return false;
119        int width = Integer.parseInt(candidate.substring(0, index));
120        int height = Integer.parseInt(candidate.substring(index + 1));
121        for (Size size: supported) {
122            if (size.width == width && size.height == height) {
123                parameters.setPictureSize(width, height);
124                return true;
125            }
126        }
127        return false;
128    }
129
130    private void initPreference(PreferenceGroup group) {
131        ListPreference videoQuality = group.findPreference(KEY_VIDEO_QUALITY);
132        ListPreference videoTimeLapseQuality = group.findPreference(KEY_VIDEO_TIME_LAPSE_QUALITY);
133        ListPreference pictureSize = group.findPreference(KEY_PICTURE_SIZE);
134        ListPreference whiteBalance =  group.findPreference(KEY_WHITE_BALANCE);
135        ListPreference colorEffect = group.findPreference(KEY_COLOR_EFFECT);
136        ListPreference sceneMode = group.findPreference(KEY_SCENE_MODE);
137        ListPreference flashMode = group.findPreference(KEY_FLASH_MODE);
138        ListPreference focusMode = group.findPreference(KEY_FOCUS_MODE);
139        ListPreference exposure = group.findPreference(KEY_EXPOSURE);
140        IconListPreference cameraIdPref =
141                (IconListPreference)group.findPreference(KEY_CAMERA_ID);
142        ListPreference videoFlashMode =
143                group.findPreference(KEY_VIDEOCAMERA_FLASH_MODE);
144
145        // Since the screen could be loaded from different resources, we need
146        // to check if the preference is available here
147        if (videoQuality != null) {
148            initVideoQuality(videoQuality);
149        }
150
151        // Filter out unsupported settings / options
152        if (videoTimeLapseQuality != null) {
153            filterUnsupportedOptions(group, videoTimeLapseQuality,
154                    getSupportedTimeLapseProfiles(mCameraId));
155        }
156        if (pictureSize != null) {
157            filterUnsupportedOptions(group, pictureSize, sizeListToStringList(
158                    mParameters.getSupportedPictureSizes()));
159        }
160        if (whiteBalance != null) {
161            filterUnsupportedOptions(group,
162                    whiteBalance, mParameters.getSupportedWhiteBalance());
163        }
164        if (colorEffect != null) {
165            filterUnsupportedOptions(group,
166                    colorEffect, mParameters.getSupportedColorEffects());
167        }
168        if (sceneMode != null) {
169            filterUnsupportedOptions(group,
170                    sceneMode, mParameters.getSupportedSceneModes());
171        }
172        if (flashMode != null) {
173            filterUnsupportedOptions(group,
174                    flashMode, mParameters.getSupportedFlashModes());
175        }
176        if (focusMode != null) {
177            filterUnsupportedOptions(group,
178                    focusMode, mParameters.getSupportedFocusModes());
179        }
180        if (videoFlashMode != null) {
181            filterUnsupportedOptions(group,
182                    videoFlashMode, mParameters.getSupportedFlashModes());
183        }
184        if (exposure != null) buildExposureCompensation(group, exposure);
185        if (cameraIdPref != null) buildCameraId(group, cameraIdPref);
186    }
187
188    private static List<String> getSupportedTimeLapseProfiles(int cameraId) {
189        ArrayList<String> supportedProfiles = new ArrayList<String>();
190        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_480P)) {
191            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_480P));
192        }
193        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_720P)) {
194            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_720P));
195        }
196        if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_TIME_LAPSE_1080P)) {
197            supportedProfiles.add(Integer.toString(CamcorderProfile.QUALITY_TIME_LAPSE_1080P));
198        }
199
200        return supportedProfiles;
201    }
202
203    private void buildExposureCompensation(
204            PreferenceGroup group, ListPreference exposure) {
205        int max = mParameters.getMaxExposureCompensation();
206        int min = mParameters.getMinExposureCompensation();
207        if (max == 0 && min == 0) {
208            removePreference(group, exposure.getKey());
209            return;
210        }
211        float step = mParameters.getExposureCompensationStep();
212
213        // show only integer values for exposure compensation
214        int maxValue = (int) Math.floor(max * step);
215        int minValue = (int) Math.ceil(min * step);
216        CharSequence entries[] = new CharSequence[maxValue - minValue + 1];
217        CharSequence entryValues[] = new CharSequence[maxValue - minValue + 1];
218        for (int i = minValue; i <= maxValue; ++i) {
219            entryValues[maxValue - i] = Integer.toString(Math.round(i / step));
220            StringBuilder builder = new StringBuilder();
221            if (i > 0) builder.append('+');
222            entries[maxValue - i] = builder.append(i).toString();
223        }
224        exposure.setEntries(entries);
225        exposure.setEntryValues(entryValues);
226    }
227
228    private void buildCameraId(
229            PreferenceGroup group, IconListPreference preference) {
230        int numOfCameras = mCameraInfo.length;
231        if (numOfCameras < 2) {
232            removePreference(group, preference.getKey());
233            return;
234        }
235
236        CharSequence[] entryValues = new CharSequence[2];
237        for (int i = 0 ; i < mCameraInfo.length ; ++i) {
238            int index =
239                    (mCameraInfo[i].facing == CameraInfo.CAMERA_FACING_FRONT)
240                    ? CameraInfo.CAMERA_FACING_FRONT
241                    : CameraInfo.CAMERA_FACING_BACK;
242            if (entryValues[index] == null) {
243                entryValues[index] = "" + i;
244                if (entryValues[((index == 1) ? 0 : 1)] != null) break;
245            }
246        }
247        preference.setEntryValues(entryValues);
248    }
249
250    private static boolean removePreference(PreferenceGroup group, String key) {
251        for (int i = 0, n = group.size(); i < n; i++) {
252            CameraPreference child = group.get(i);
253            if (child instanceof PreferenceGroup) {
254                if (removePreference((PreferenceGroup) child, key)) {
255                    return true;
256                }
257            }
258            if (child instanceof ListPreference &&
259                    ((ListPreference) child).getKey().equals(key)) {
260                group.removePreference(i);
261                return true;
262            }
263        }
264        return false;
265    }
266
267    private void filterUnsupportedOptions(PreferenceGroup group,
268            ListPreference pref, List<String> supported) {
269
270        // Remove the preference if the parameter is not supported or there is
271        // only one options for the settings.
272        if (supported == null || supported.size() <= 1) {
273            removePreference(group, pref.getKey());
274            return;
275        }
276
277        pref.filterUnsupported(supported);
278        if (pref.getEntries().length <= 1) {
279            removePreference(group, pref.getKey());
280            return;
281        }
282
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