CameraSettings.java revision 6988d4e2ef8d14d8bf3ee81c8eb3175bbf1b88ec
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.graphics.drawable.Drawable;
23import android.hardware.Camera.Parameters;
24import android.hardware.Camera.Size;
25import android.media.CamcorderProfile;
26import android.preference.PreferenceManager;
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_RECORD_LOCATION = RecordLocationPreference.KEY;
40    public static final String KEY_VIDEO_QUALITY = "pref_video_quality_key";
41    public static final String KEY_PICTURE_SIZE = "pref_camera_picturesize_key";
42    public static final String KEY_JPEG_QUALITY = "pref_camera_jpegquality_key";
43    public static final String KEY_FOCUS_MODE = "pref_camera_focusmode_key";
44    public static final String KEY_FLASH_MODE = "pref_camera_flashmode_key";
45    public static final String KEY_VIDEOCAMERA_FLASH_MODE = "pref_camera_video_flashmode_key";
46    public static final String KEY_COLOR_EFFECT = "pref_camera_coloreffect_key";
47    public static final String KEY_WHITE_BALANCE = "pref_camera_whitebalance_key";
48    public static final String KEY_SCENE_MODE = "pref_camera_scenemode_key";
49    public static final String KEY_QUICK_CAPTURE = "pref_camera_quickcapture_key";
50    public static final String KEY_EXPOSURE = "pref_camera_exposure_key";
51
52    public static final String QUICK_CAPTURE_ON = "on";
53    public static final String QUICK_CAPTURE_OFF = "off";
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 int CURRENT_VERSION = 4;
60
61    // max video duration in seconds for mms and youtube.
62    private static final int MMS_VIDEO_DURATION = CamcorderProfile.getMmsRecordingDurationInSeconds();
63    private static final int YOUTUBE_VIDEO_DURATION = 10 * 60; // 10 mins
64    private static final int DEFAULT_VIDEO_DURATION = 30 * 60; // 10 mins
65
66    public static final String DEFAULT_VIDEO_QUALITY_VALUE = "high";
67
68    // MMS video length
69    public static final int DEFAULT_VIDEO_DURATION_VALUE = -1;
70
71    @SuppressWarnings("unused")
72    private static final String TAG = "CameraSettings";
73
74    private final Context mContext;
75    private final Parameters mParameters;
76
77    public CameraSettings(Activity activity, Parameters parameters) {
78        mContext = activity;
79        mParameters = parameters;
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 = PreferenceManager
101                        .getDefaultSharedPreferences(context).edit();
102                editor.putString(KEY_PICTURE_SIZE, candidate);
103                editor.commit();
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 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        ListPreference videoFlashMode =
140                group.findPreference(KEY_VIDEOCAMERA_FLASH_MODE);
141
142        // Since the screen could be loaded from different resources, we need
143        // to check if the preference is available here
144        if (videoQuality != null) {
145            // Modify video duration settings.
146            // The first entry is for MMS video duration, and we need to fill
147            // in the device-dependent value (in seconds).
148            CharSequence[] entries = videoQuality.getEntries();
149            CharSequence[] values = videoQuality.getEntryValues();
150            for (int i = 0; i < entries.length; ++i) {
151                if (VIDEO_QUALITY_MMS.equals(values[i])) {
152                    entries[i] = entries[i].toString().replace(
153                            "30", Integer.toString(MMS_VIDEO_DURATION));
154                    break;
155                }
156            }
157        }
158
159        // Filter out unsupported settings / options
160        if (pictureSize != null) {
161            filterUnsupportedOptions(group, pictureSize, sizeListToStringList(
162                    mParameters.getSupportedPictureSizes()));
163        }
164        if (whiteBalance != null) {
165            filterUnsupportedOptions(group,
166                    whiteBalance, mParameters.getSupportedWhiteBalance());
167        }
168        if (colorEffect != null) {
169            filterUnsupportedOptions(group,
170                    colorEffect, mParameters.getSupportedColorEffects());
171        }
172        if (sceneMode != null) {
173            filterUnsupportedOptions(group,
174                    sceneMode, mParameters.getSupportedSceneModes());
175        }
176        if (flashMode != null) {
177            filterUnsupportedOptions(group,
178                    flashMode, mParameters.getSupportedFlashModes());
179        }
180        if (focusMode != null) {
181            filterUnsupportedOptions(group,
182                    focusMode, mParameters.getSupportedFocusModes());
183        }
184        if (videoFlashMode != null) {
185            filterUnsupportedOptions(group,
186                    videoFlashMode, mParameters.getSupportedFlashModes());
187        }
188
189        if (exposure != null) {
190            buildExposureCompensation(group, exposure);
191        }
192    }
193
194    private void buildExposureCompensation(
195            PreferenceGroup group, ListPreference exposure) {
196        int max = mParameters.getMaxExposureCompensation();
197        int min = mParameters.getMinExposureCompensation();
198        if (max == 0 && min == 0) {
199            removePreference(group, exposure.getKey());
200            return;
201        }
202        float step = mParameters.getExposureCompensationStep();
203
204        // show only integer values for exposure compensation
205        int maxValue = (int) Math.floor(max * step);
206        int minValue = (int) Math.ceil(min * step);
207        CharSequence entries[] = new CharSequence[maxValue - minValue + 1];
208        CharSequence entryValues[] = new CharSequence[maxValue - minValue + 1];
209        for (int i = minValue; i <= maxValue; ++i) {
210            entryValues[maxValue - i] = Integer.toString(Math.round(i / step));
211            StringBuilder builder = new StringBuilder();
212            if (i > 0) builder.append('+');
213            entries[maxValue - i] = builder.append(i).toString();
214        }
215        exposure.setEntries(entries);
216        exposure.setEntryValues(entryValues);
217    }
218
219    private static boolean removePreference(PreferenceGroup group, String key) {
220        for (int i = 0, n = group.size(); i < n; i++) {
221            CameraPreference child = group.get(i);
222            if (child instanceof PreferenceGroup) {
223                if (removePreference((PreferenceGroup) child, key)) {
224                    return true;
225                }
226            }
227            if (child instanceof ListPreference &&
228                    ((ListPreference) child).getKey().equals(key)) {
229                group.removePreference(i);
230                return true;
231            }
232        }
233        return false;
234    }
235
236    private void filterUnsupportedOptions(PreferenceGroup group,
237            ListPreference pref, List<String> supported) {
238
239        CharSequence[] allEntries = pref.getEntries();
240
241        // Remove the preference if the parameter is not supported or there is
242        // only one options for the settings.
243        if (supported == null || supported.size() <= 1) {
244            removePreference(group, pref.getKey());
245            return;
246        }
247
248        CharSequence[] allEntryValues = pref.getEntryValues();
249        Drawable[] allIcons = (pref instanceof IconListPreference)
250                ? ((IconListPreference) pref).getIcons()
251                : null;
252        ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
253        ArrayList<CharSequence> entryValues = new ArrayList<CharSequence>();
254        ArrayList<Drawable> icons =
255                allIcons == null ? null : new ArrayList<Drawable>();
256        for (int i = 0, len = allEntryValues.length; i < len; i++) {
257            if (supported.indexOf(allEntryValues[i].toString()) != NOT_FOUND) {
258                entries.add(allEntries[i]);
259                entryValues.add(allEntryValues[i]);
260                if (allIcons != null) icons.add(allIcons[i]);
261            }
262        }
263
264        // Set entries and entry values to list preference.
265        int size = entries.size();
266        pref.setEntries(entries.toArray(new CharSequence[size]));
267        pref.setEntryValues(entryValues.toArray(new CharSequence[size]));
268        if (allIcons != null) {
269            ((IconListPreference) pref)
270                    .setIcons(icons.toArray(new Drawable[size]));
271        }
272
273        // Set the value to the first entry if it is invalid.
274        String value = pref.getValue();
275        if (pref.findIndexOfValue(value) == NOT_FOUND) {
276            pref.setValueIndex(0);
277        }
278    }
279
280    private static List<String> sizeListToStringList(List<Size> sizes) {
281        ArrayList<String> list = new ArrayList<String>();
282        for (Size size : sizes) {
283            list.add(String.format("%dx%d", size.width, size.height));
284        }
285        return list;
286    }
287
288    public static void upgradePreferences(SharedPreferences pref) {
289        int version;
290        try {
291            version = pref.getInt(KEY_VERSION, 0);
292        } catch (Exception ex) {
293            version = 0;
294        }
295        if (version == CURRENT_VERSION) return;
296
297        SharedPreferences.Editor editor = pref.edit();
298        if (version == 0) {
299            // We won't use the preference which change in version 1.
300            // So, just upgrade to version 1 directly
301            version = 1;
302        }
303        if (version == 1) {
304            // Change jpeg quality {65,75,85} to {normal,fine,superfine}
305            String quality = pref.getString(KEY_JPEG_QUALITY, "85");
306            if (quality.equals("65")) {
307                quality = "normal";
308            } else if (quality.equals("75")) {
309                quality = "fine";
310            } else {
311                quality = "superfine";
312            }
313            editor.putString(KEY_JPEG_QUALITY, quality);
314            version = 2;
315        }
316        if (version == 2) {
317            editor.putString(KEY_RECORD_LOCATION,
318                    pref.getBoolean(KEY_RECORD_LOCATION, false)
319                    ? RecordLocationPreference.VALUE_ON
320                    : RecordLocationPreference.VALUE_NONE);
321            version = 3;
322        }
323        if (version == 3) {
324            // Just use video quality to replace it and
325            // ignore the current settings.
326            editor.remove("pref_camera_videoquality_key");
327            editor.remove("pref_camera_video_duration_key");
328        }
329        editor.putInt(KEY_VERSION, CURRENT_VERSION);
330        editor.commit();
331    }
332
333    public static boolean getVideoQuality(String quality) {
334        return VIDEO_QUALITY_YOUTUBE.equals(
335                quality) || VIDEO_QUALITY_HIGH.equals(quality);
336    }
337
338    public static int getVidoeDurationInMillis(String quality) {
339        if (VIDEO_QUALITY_MMS.equals(quality)) {
340            return MMS_VIDEO_DURATION * 1000;
341        } else if (VIDEO_QUALITY_YOUTUBE.equals(quality)) {
342            return YOUTUBE_VIDEO_DURATION * 1000;
343        }
344        return DEFAULT_VIDEO_DURATION * 1000;
345    }
346}
347