Camera.java revision da0a56df963353a1f1bd1914fa31f870d982dd5a
1/*
2 * Copyright (C) 2008 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 android.hardware;
18
19import java.lang.ref.WeakReference;
20import java.util.ArrayList;
21import java.util.HashMap;
22import java.util.List;
23import java.util.StringTokenizer;
24import java.io.IOException;
25
26import android.util.Log;
27import android.view.Surface;
28import android.view.SurfaceHolder;
29import android.graphics.PixelFormat;
30import android.os.Handler;
31import android.os.Looper;
32import android.os.Message;
33
34/**
35 * The Camera class is used to connect/disconnect with the camera service,
36 * set capture settings, start/stop preview, snap a picture, and retrieve
37 * frames for encoding for video.
38 * <p>There is no default constructor for this class. Use {@link #open()} to
39 * get a Camera object.</p>
40 *
41 * <p>In order to use the device camera, you must declare the
42 * {@link android.Manifest.permission#CAMERA} permission in your Android
43 * Manifest. Also be sure to include the
44 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature></a>
45 * manifest element in order to declare camera features used by your application.
46 * For example, if you use the camera and auto-focus feature, your Manifest
47 * should include the following:</p>
48 * <pre> &lt;uses-permission android:name="android.permission.CAMERA" />
49 * &lt;uses-feature android:name="android.hardware.camera" />
50 * &lt;uses-feature android:name="android.hardware.camera.autofocus" /></pre>
51 *
52 * <p class="caution"><strong>Caution:</strong> Different Android-powered devices
53 * may have different hardware specifications, such as megapixel ratings and
54 * auto-focus capabilities. In order for your application to be compatible with
55 * more devices, you should not make assumptions about the device camera
56 * specifications.</p>
57 */
58public class Camera {
59    private static final String TAG = "Camera";
60
61    // These match the enums in frameworks/base/include/ui/Camera.h
62    private static final int CAMERA_MSG_ERROR            = 0x001;
63    private static final int CAMERA_MSG_SHUTTER          = 0x002;
64    private static final int CAMERA_MSG_FOCUS            = 0x004;
65    private static final int CAMERA_MSG_ZOOM             = 0x008;
66    private static final int CAMERA_MSG_PREVIEW_FRAME    = 0x010;
67    private static final int CAMERA_MSG_VIDEO_FRAME      = 0x020;
68    private static final int CAMERA_MSG_POSTVIEW_FRAME   = 0x040;
69    private static final int CAMERA_MSG_RAW_IMAGE        = 0x080;
70    private static final int CAMERA_MSG_COMPRESSED_IMAGE = 0x100;
71    private static final int CAMERA_MSG_ALL_MSGS         = 0x1FF;
72
73    private int mNativeContext; // accessed by native methods
74    private EventHandler mEventHandler;
75    private ShutterCallback mShutterCallback;
76    private PictureCallback mRawImageCallback;
77    private PictureCallback mJpegCallback;
78    private PreviewCallback mPreviewCallback;
79    private PictureCallback mPostviewCallback;
80    private AutoFocusCallback mAutoFocusCallback;
81    private ZoomCallback mZoomCallback;
82    private ErrorCallback mErrorCallback;
83    private boolean mOneShot;
84
85    /**
86     * Returns a new Camera object.
87     */
88    public static Camera open() {
89        return new Camera();
90    }
91
92    Camera() {
93        mShutterCallback = null;
94        mRawImageCallback = null;
95        mJpegCallback = null;
96        mPreviewCallback = null;
97        mPostviewCallback = null;
98        mZoomCallback = null;
99
100        Looper looper;
101        if ((looper = Looper.myLooper()) != null) {
102            mEventHandler = new EventHandler(this, looper);
103        } else if ((looper = Looper.getMainLooper()) != null) {
104            mEventHandler = new EventHandler(this, looper);
105        } else {
106            mEventHandler = null;
107        }
108
109        native_setup(new WeakReference<Camera>(this));
110    }
111
112    protected void finalize() {
113        native_release();
114    }
115
116    private native final void native_setup(Object camera_this);
117    private native final void native_release();
118
119
120    /**
121     * Disconnects and releases the Camera object resources.
122     * <p>It is recommended that you call this as soon as you're done with the
123     * Camera object.</p>
124     */
125    public final void release() {
126        native_release();
127    }
128
129    /**
130     * Reconnect to the camera after passing it to MediaRecorder. To save
131     * setup/teardown time, a client of Camera can pass an initialized Camera
132     * object to a MediaRecorder to use for video recording. Once the
133     * MediaRecorder is done with the Camera, this method can be used to
134     * re-establish a connection with the camera hardware. NOTE: The Camera
135     * object must first be unlocked by the process that owns it before it
136     * can be connected to another process.
137     *
138     * @throws IOException if the method fails.
139     *
140     * FIXME: Unhide after approval
141     * @hide
142     */
143    public native final void reconnect() throws IOException;
144
145    /**
146     * Lock the camera to prevent other processes from accessing it. To save
147     * setup/teardown time, a client of Camera can pass an initialized Camera
148     * object to another process. This method is used to re-lock the Camera
149     * object prevent other processes from accessing it. By default, the
150     * Camera object is locked. Locking it again from the same process will
151     * have no effect. Attempting to lock it from another process if it has
152     * not been unlocked will fail.
153     * Returns 0 if lock was successful.
154     *
155     * FIXME: Unhide after approval
156     * @hide
157     */
158    public native final int lock();
159
160    /**
161     * Unlock the camera to allow another process to access it. To save
162     * setup/teardown time, a client of Camera can pass an initialized Camera
163     * object to another process. This method is used to unlock the Camera
164     * object before handing off the Camera object to the other process.
165
166     * Returns 0 if unlock was successful.
167     *
168     * FIXME: Unhide after approval
169     * @hide
170     */
171    public native final int unlock();
172
173    /**
174     * Sets the SurfaceHolder to be used for a picture preview. If the surface
175     * changed since the last call, the screen will blank. Nothing happens
176     * if the same surface is re-set.
177     *
178     * @param holder the SurfaceHolder upon which to place the picture preview
179     * @throws IOException if the method fails.
180     */
181    public final void setPreviewDisplay(SurfaceHolder holder) throws IOException {
182        if (holder != null) {
183            setPreviewDisplay(holder.getSurface());
184        } else {
185            setPreviewDisplay((Surface)null);
186        }
187    }
188
189    private native final void setPreviewDisplay(Surface surface);
190
191    /**
192     * Used to get a copy of each preview frame.
193     */
194    public interface PreviewCallback
195    {
196        /**
197         * The callback that delivers the preview frames.
198         *
199         * @param data The contents of the preview frame in the format defined
200         *  by {@link android.graphics.PixelFormat}, which can be queried
201         *  with {@link android.hardware.Camera.Parameters#getPreviewFormat()}.
202         *  If {@link android.hardware.Camera.Parameters#setPreviewFormat(int)}
203         *             is never called, the default will be the YCbCr_420_SP
204         *             (NV21) format.
205         * @param camera The Camera service object.
206         */
207        void onPreviewFrame(byte[] data, Camera camera);
208    };
209
210    /**
211     * Start drawing preview frames to the surface.
212     */
213    public native final void startPreview();
214
215    /**
216     * Stop drawing preview frames to the surface.
217     */
218    public native final void stopPreview();
219
220    /**
221     * Return current preview state.
222     *
223     * FIXME: Unhide before release
224     * @hide
225     */
226    public native final boolean previewEnabled();
227
228    /**
229     * Can be called at any time to instruct the camera to use a callback for
230     * each preview frame in addition to displaying it.
231     *
232     * @param cb A callback object that receives a copy of each preview frame.
233     *           Pass null to stop receiving callbacks at any time.
234     */
235    public final void setPreviewCallback(PreviewCallback cb) {
236        mPreviewCallback = cb;
237        mOneShot = false;
238        setHasPreviewCallback(cb != null, false);
239    }
240
241    /**
242     * Installs a callback to retrieve a single preview frame, after which the
243     * callback is cleared.
244     *
245     * @param cb A callback object that receives a copy of the preview frame.
246     */
247    public final void setOneShotPreviewCallback(PreviewCallback cb) {
248        if (cb != null) {
249            mPreviewCallback = cb;
250            mOneShot = true;
251            setHasPreviewCallback(true, true);
252        }
253    }
254
255    private native final void setHasPreviewCallback(boolean installed, boolean oneshot);
256
257    private class EventHandler extends Handler
258    {
259        private Camera mCamera;
260
261        public EventHandler(Camera c, Looper looper) {
262            super(looper);
263            mCamera = c;
264        }
265
266        @Override
267        public void handleMessage(Message msg) {
268            switch(msg.what) {
269            case CAMERA_MSG_SHUTTER:
270                if (mShutterCallback != null) {
271                    mShutterCallback.onShutter();
272                }
273                return;
274
275            case CAMERA_MSG_RAW_IMAGE:
276                if (mRawImageCallback != null) {
277                    mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera);
278                }
279                return;
280
281            case CAMERA_MSG_COMPRESSED_IMAGE:
282                if (mJpegCallback != null) {
283                    mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera);
284                }
285                return;
286
287            case CAMERA_MSG_PREVIEW_FRAME:
288                if (mPreviewCallback != null) {
289                    mPreviewCallback.onPreviewFrame((byte[])msg.obj, mCamera);
290                    if (mOneShot) {
291                        mPreviewCallback = null;
292                    }
293                }
294                return;
295
296            case CAMERA_MSG_POSTVIEW_FRAME:
297                if (mPostviewCallback != null) {
298                    mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera);
299                }
300                return;
301
302            case CAMERA_MSG_FOCUS:
303                if (mAutoFocusCallback != null) {
304                    mAutoFocusCallback.onAutoFocus(msg.arg1 == 0 ? false : true, mCamera);
305                }
306                return;
307
308            case CAMERA_MSG_ZOOM:
309                if (mZoomCallback != null) {
310                    mZoomCallback.onZoomUpdate(msg.arg1, mCamera);
311                }
312                return;
313
314            case CAMERA_MSG_ERROR :
315                Log.e(TAG, "Error " + msg.arg1);
316                if (mErrorCallback != null) {
317                    mErrorCallback.onError(msg.arg1, mCamera);
318                }
319                return;
320
321            default:
322                Log.e(TAG, "Unknown message type " + msg.what);
323                return;
324            }
325        }
326    }
327
328    private static void postEventFromNative(Object camera_ref,
329                                            int what, int arg1, int arg2, Object obj)
330    {
331        Camera c = (Camera)((WeakReference)camera_ref).get();
332        if (c == null)
333            return;
334
335        if (c.mEventHandler != null) {
336            Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj);
337            c.mEventHandler.sendMessage(m);
338        }
339    }
340
341    /**
342     * Handles the callback for the camera auto focus.
343     * <p>Devices that do not support auto-focus will receive a "fake"
344     * callback to this interface. If your application needs auto-focus and
345     * should not be installed on devices <em>without</em> auto-focus, you must
346     * declare that your app uses the
347     * {@code android.hardware.camera.autofocus} feature, in the
348     * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature></a>
349     * manifest element.</p>
350     */
351    public interface AutoFocusCallback
352    {
353        /**
354         * Callback for the camera auto focus. If the camera does not support
355         * auto-focus and autoFocus is called, onAutoFocus will be called
356         * immediately with success.
357         *
358         * @param success true if focus was successful, false if otherwise
359         * @param camera  the Camera service object
360         */
361        void onAutoFocus(boolean success, Camera camera);
362    };
363
364    /**
365     * Starts auto-focus function and registers a callback function to run when
366     * camera is focused. Only valid after startPreview() has been called. If
367     * the camera does not support auto-focus, it is a no-op and {@link
368     * AutoFocusCallback#onAutoFocus(boolean, Camera)} callback will be called
369     * immediately.
370     * <p>If your application should not be installed
371     * on devices without auto-focus, you must declare that your application
372     * uses auto-focus with the
373     * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature></a>
374     * manifest element.</p>
375     *
376     * @param cb the callback to run
377     */
378    public final void autoFocus(AutoFocusCallback cb)
379    {
380        mAutoFocusCallback = cb;
381        native_autoFocus();
382    }
383    private native final void native_autoFocus();
384
385    /**
386     * An interface which contains a callback for the shutter closing after taking a picture.
387     */
388    public interface ShutterCallback
389    {
390        /**
391         * Can be used to play a shutter sound as soon as the image has been captured, but before
392         * the data is available.
393         */
394        void onShutter();
395    }
396
397    /**
398     * Handles the callback for when a picture is taken.
399     */
400    public interface PictureCallback {
401        /**
402         * Callback for when a picture is taken.
403         *
404         * @param data   a byte array of the picture data
405         * @param camera the Camera service object
406         */
407        void onPictureTaken(byte[] data, Camera camera);
408    };
409
410    /**
411     * Triggers an asynchronous image capture. The camera service will initiate
412     * a series of callbacks to the application as the image capture progresses.
413     * The shutter callback occurs after the image is captured. This can be used
414     * to trigger a sound to let the user know that image has been captured. The
415     * raw callback occurs when the raw image data is available (NOTE: the data
416     * may be null if the hardware does not have enough memory to make a copy).
417     * The jpeg callback occurs when the compressed image is available. If the
418     * application does not need a particular callback, a null can be passed
419     * instead of a callback method.
420     *
421     * @param shutter   callback after the image is captured, may be null
422     * @param raw       callback with raw image data, may be null
423     * @param jpeg      callback with jpeg image data, may be null
424     */
425    public final void takePicture(ShutterCallback shutter, PictureCallback raw,
426            PictureCallback jpeg) {
427        takePicture(shutter, raw, null, jpeg);
428    }
429    private native final void native_takePicture();
430
431    /**
432     * Triggers an asynchronous image capture. The camera service will initiate
433     * a series of callbacks to the application as the image capture progresses.
434     * The shutter callback occurs after the image is captured. This can be used
435     * to trigger a sound to let the user know that image has been captured. The
436     * raw callback occurs when the raw image data is available (NOTE: the data
437     * may be null if the hardware does not have enough memory to make a copy).
438     * The postview callback occurs when a scaled, fully processed postview
439     * image is available (NOTE: not all hardware supports this). The jpeg
440     * callback occurs when the compressed image is available. If the
441     * application does not need a particular callback, a null can be passed
442     * instead of a callback method.
443     *
444     * @param shutter   callback after the image is captured, may be null
445     * @param raw       callback with raw image data, may be null
446     * @param postview  callback with postview image data, may be null
447     * @param jpeg      callback with jpeg image data, may be null
448     */
449    public final void takePicture(ShutterCallback shutter, PictureCallback raw,
450            PictureCallback postview, PictureCallback jpeg) {
451        mShutterCallback = shutter;
452        mRawImageCallback = raw;
453        mPostviewCallback = postview;
454        mJpegCallback = jpeg;
455        native_takePicture();
456    }
457
458    /**
459     * Handles the zoom callback.
460     */
461    public interface ZoomCallback
462    {
463        /**
464         * Callback for zoom updates
465         * @param zoomLevel   new zoom level in 1/1000 increments,
466         * e.g. a zoom of 3.2x is stored as 3200. Accuracy of the
467         * value is dependent on the hardware implementation. Not
468         * all devices will generate this callback.
469         * @param camera  the Camera service object
470         */
471        void onZoomUpdate(int zoomLevel, Camera camera);
472    };
473
474    /**
475     * Registers a callback to be invoked when the zoom
476     * level is updated by the camera driver.
477     * @param cb the callback to run
478     */
479    public final void setZoomCallback(ZoomCallback cb)
480    {
481        mZoomCallback = cb;
482    }
483
484    // These match the enum in include/ui/Camera.h
485    /** Unspecified camerar error.  @see #ErrorCallback */
486    public static final int CAMERA_ERROR_UNKNOWN = 1;
487    /** Media server died. In this case, the application must release the
488     * Camera object and instantiate a new one. @see #ErrorCallback */
489    public static final int CAMERA_ERROR_SERVER_DIED = 100;
490
491    /**
492     * Handles the camera error callback.
493     */
494    public interface ErrorCallback
495    {
496        /**
497         * Callback for camera errors.
498         * @param error   error code:
499         * <ul>
500         * <li>{@link #CAMERA_ERROR_UNKNOWN}
501         * <li>{@link #CAMERA_ERROR_SERVER_DIED}
502         * </ul>
503         * @param camera  the Camera service object
504         */
505        void onError(int error, Camera camera);
506    };
507
508    /**
509     * Registers a callback to be invoked when an error occurs.
510     * @param cb the callback to run
511     */
512    public final void setErrorCallback(ErrorCallback cb)
513    {
514        mErrorCallback = cb;
515    }
516
517    private native final void native_setParameters(String params);
518    private native final String native_getParameters();
519
520    /**
521     * Sets the Parameters for pictures from this Camera service.
522     *
523     * @param params the Parameters to use for this Camera service
524     */
525    public void setParameters(Parameters params) {
526        native_setParameters(params.flatten());
527    }
528
529    /**
530     * Returns the picture Parameters for this Camera service.
531     */
532    public Parameters getParameters() {
533        Parameters p = new Parameters();
534        String s = native_getParameters();
535        p.unflatten(s);
536        return p;
537    }
538
539    /**
540     * Handles the picture size (dimensions).
541     */
542    public class Size {
543        /**
544         * Sets the dimensions for pictures.
545         *
546         * @param w the photo width (pixels)
547         * @param h the photo height (pixels)
548         */
549        public Size(int w, int h) {
550            width = w;
551            height = h;
552        }
553        /** width of the picture */
554        public int width;
555        /** height of the picture */
556        public int height;
557    };
558
559    /**
560     * Handles the parameters for pictures created by a Camera service.
561     *
562     * <p>To make camera parameters take effect, applications have to call
563     * Camera.setParameters. For example, after setWhiteBalance is called, white
564     * balance is not changed until Camera.setParameters() is called.
565     *
566     * <p>Different devices may have different camera capabilities, such as
567     * picture size or flash modes. The application should query the camera
568     * capabilities before setting parameters. For example, the application
569     * should call getSupportedColorEffects before calling setEffect. If the
570     * camera does not support color effects, getSupportedColorEffects will
571     * return null.
572     */
573    public class Parameters {
574        // Parameter keys to communicate with the camera driver.
575        private static final String KEY_PREVIEW_SIZE = "preview-size";
576        private static final String KEY_PREVIEW_FORMAT = "preview-format";
577        private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate";
578        private static final String KEY_PICTURE_SIZE = "picture-size";
579        private static final String KEY_PICTURE_FORMAT = "picture-format";
580        private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width";
581        private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height";
582        private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality";
583        private static final String KEY_JPEG_QUALITY = "jpeg-quality";
584        private static final String KEY_ROTATION = "rotation";
585        private static final String KEY_GPS_LATITUDE = "gps-latitude";
586        private static final String KEY_GPS_LONGITUDE = "gps-longitude";
587        private static final String KEY_GPS_ALTITUDE = "gps-altitude";
588        private static final String KEY_GPS_TIMESTAMP = "gps-timestamp";
589        private static final String KEY_WHITE_BALANCE = "whitebalance";
590        private static final String KEY_EFFECT = "effect";
591        private static final String KEY_ANTIBANDING = "antibanding";
592        private static final String KEY_SCENE_MODE = "scene-mode";
593        private static final String KEY_FLASH_MODE = "flash-mode";
594        // Parameter key suffix for supported values.
595        private static final String SUPPORTED_VALUES_SUFFIX = "-values";
596
597        // Values for white balance settings.
598        public static final String WHITE_BALANCE_AUTO = "auto";
599        public static final String WHITE_BALANCE_INCANDESCENT = "incandescent";
600        public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent";
601        public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent";
602        public static final String WHITE_BALANCE_DAYLIGHT = "daylight";
603        public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight";
604        public static final String WHITE_BALANCE_TWILIGHT = "twilight";
605        public static final String WHITE_BALANCE_SHADE = "shade";
606
607        // Values for color effect settings.
608        public static final String EFFECT_NONE = "none";
609        public static final String EFFECT_MONO = "mono";
610        public static final String EFFECT_NEGATIVE = "negative";
611        public static final String EFFECT_SOLARIZE = "solarize";
612        public static final String EFFECT_SEPIA = "sepia";
613        public static final String EFFECT_POSTERIZE = "posterize";
614        public static final String EFFECT_WHITEBOARD = "whiteboard";
615        public static final String EFFECT_BLACKBOARD = "blackboard";
616        public static final String EFFECT_AQUA = "aqua";
617
618        // Values for antibanding settings.
619        public static final String ANTIBANDING_AUTO = "auto";
620        public static final String ANTIBANDING_50HZ = "50hz";
621        public static final String ANTIBANDING_60HZ = "60hz";
622        public static final String ANTIBANDING_OFF = "off";
623
624        // Values for flash mode settings.
625        /**
626         * Flash will not be fired.
627         */
628        public static final String FLASH_MODE_OFF = "off";
629        /**
630         * Flash will be fired automatically when required. The timing is
631         * decided by camera driver.
632         */
633        public static final String FLASH_MODE_AUTO = "auto";
634        /**
635         * Flash will always be fired. The timing is decided by camera driver.
636         */
637        public static final String FLASH_MODE_ON = "on";
638        /**
639         * Flash will be fired in red-eye reduction mode.
640         */
641        public static final String FLASH_MODE_RED_EYE = "red-eye";
642
643        // Values for scene mode settings.
644        public static final String SCENE_MODE_AUTO = "auto";
645        public static final String SCENE_MODE_ACTION = "action";
646        public static final String SCENE_MODE_PORTRAIT = "portrait";
647        public static final String SCENE_MODE_LANDSCAPE = "landscape";
648        public static final String SCENE_MODE_NIGHT = "night";
649        public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait";
650        public static final String SCENE_MODE_THEATRE = "theatre";
651        public static final String SCENE_MODE_BEACH = "beach";
652        public static final String SCENE_MODE_SNOW = "snow";
653        public static final String SCENE_MODE_SUNSET = "sunset";
654        public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto";
655        public static final String SCENE_MODE_FIREWORKS = "fireworks";
656        public static final String SCENE_MODE_SPORTS = "sports";
657        public static final String SCENE_MODE_PARTY = "party";
658        public static final String SCENE_MODE_CANDLELIGHT = "candlelight";
659
660        // Formats for setPreviewFormat and setPictureFormat.
661        private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp";
662        private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp";
663        private static final String PIXEL_FORMAT_RGB565 = "rgb565";
664        private static final String PIXEL_FORMAT_JPEG = "jpeg";
665
666        private HashMap<String, String> mMap;
667
668        private Parameters() {
669            mMap = new HashMap<String, String>();
670        }
671
672        /**
673         * Writes the current Parameters to the log.
674         * @hide
675         * @deprecated
676         */
677        public void dump() {
678            Log.e(TAG, "dump: size=" + mMap.size());
679            for (String k : mMap.keySet()) {
680                Log.e(TAG, "dump: " + k + "=" + mMap.get(k));
681            }
682        }
683
684        /**
685         * Creates a single string with all the parameters set in
686         * this Parameters object.
687         * <p>The {@link #unflatten(String)} method does the reverse.</p>
688         *
689         * @return a String with all values from this Parameters object, in
690         *         semi-colon delimited key-value pairs
691         */
692        public String flatten() {
693            StringBuilder flattened = new StringBuilder();
694            for (String k : mMap.keySet()) {
695                flattened.append(k);
696                flattened.append("=");
697                flattened.append(mMap.get(k));
698                flattened.append(";");
699            }
700            // chop off the extra semicolon at the end
701            flattened.deleteCharAt(flattened.length()-1);
702            return flattened.toString();
703        }
704
705        /**
706         * Takes a flattened string of parameters and adds each one to
707         * this Parameters object.
708         * <p>The {@link #flatten()} method does the reverse.</p>
709         *
710         * @param flattened a String of parameters (key-value paired) that
711         *                  are semi-colon delimited
712         */
713        public void unflatten(String flattened) {
714            mMap.clear();
715
716            StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
717            while (tokenizer.hasMoreElements()) {
718                String kv = tokenizer.nextToken();
719                int pos = kv.indexOf('=');
720                if (pos == -1) {
721                    continue;
722                }
723                String k = kv.substring(0, pos);
724                String v = kv.substring(pos + 1);
725                mMap.put(k, v);
726            }
727        }
728
729        public void remove(String key) {
730            mMap.remove(key);
731        }
732
733        /**
734         * Sets a String parameter.
735         *
736         * @param key   the key name for the parameter
737         * @param value the String value of the parameter
738         */
739        public void set(String key, String value) {
740            if (key.indexOf('=') != -1 || key.indexOf(';') != -1) {
741                Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ;)");
742                return;
743            }
744            if (value.indexOf('=') != -1 || value.indexOf(';') != -1) {
745                Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ;)");
746                return;
747            }
748
749            mMap.put(key, value);
750        }
751
752        /**
753         * Sets an integer parameter.
754         *
755         * @param key   the key name for the parameter
756         * @param value the int value of the parameter
757         */
758        public void set(String key, int value) {
759            mMap.put(key, Integer.toString(value));
760        }
761
762        /**
763         * Returns the value of a String parameter.
764         *
765         * @param key the key name for the parameter
766         * @return the String value of the parameter
767         */
768        public String get(String key) {
769            return mMap.get(key);
770        }
771
772        /**
773         * Returns the value of an integer parameter.
774         *
775         * @param key the key name for the parameter
776         * @return the int value of the parameter
777         */
778        public int getInt(String key) {
779            return Integer.parseInt(mMap.get(key));
780        }
781
782        /**
783         * Sets the dimensions for preview pictures.
784         *
785         * @param width  the width of the pictures, in pixels
786         * @param height the height of the pictures, in pixels
787         */
788        public void setPreviewSize(int width, int height) {
789            String v = Integer.toString(width) + "x" + Integer.toString(height);
790            set(KEY_PREVIEW_SIZE, v);
791        }
792
793        /**
794         * Returns the dimensions setting for preview pictures.
795         *
796         * @return a Size object with the height and width setting
797         *          for the preview picture
798         */
799        public Size getPreviewSize() {
800            String pair = get(KEY_PREVIEW_SIZE);
801            return strToSize(pair);
802        }
803
804        /**
805         * Gets the supported preview sizes.
806         *
807         * @return a List of Size object. null if preview size setting is not
808         *         supported.
809         */
810        public List<Size> getSupportedPreviewSizes() {
811            String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX);
812            return splitSize(str);
813        }
814
815        /**
816         * Sets the dimensions for EXIF thumbnail in Jpeg picture.
817         *
818         * @param width  the width of the thumbnail, in pixels
819         * @param height the height of the thumbnail, in pixels
820         */
821        public void setJpegThumbnailSize(int width, int height) {
822            set(KEY_JPEG_THUMBNAIL_WIDTH, width);
823            set(KEY_JPEG_THUMBNAIL_HEIGHT, height);
824        }
825
826        /**
827         * Returns the dimensions for EXIF thumbnail in Jpeg picture.
828         *
829         * @return a Size object with the height and width setting for the EXIF
830         *         thumbnails
831         */
832        public Size getJpegThumbnailSize() {
833            return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH),
834                            getInt(KEY_JPEG_THUMBNAIL_HEIGHT));
835        }
836
837        /**
838         * Sets the quality of the EXIF thumbnail in Jpeg picture.
839         *
840         * @param quality the JPEG quality of the EXIF thumbnail. The range is 1
841         *                to 100, with 100 being the best.
842         */
843        public void setJpegThumbnailQuality(int quality) {
844            set(KEY_JPEG_THUMBNAIL_QUALITY, quality);
845        }
846
847        /**
848         * Returns the quality setting for the EXIF thumbnail in Jpeg picture.
849         *
850         * @return the JPEG quality setting of the EXIF thumbnail.
851         */
852        public int getJpegThumbnailQuality() {
853            return getInt(KEY_JPEG_THUMBNAIL_QUALITY);
854        }
855
856        /**
857         * Sets Jpeg quality of captured picture.
858         *
859         * @param quality the JPEG quality of captured picture. The range is 1
860         *                to 100, with 100 being the best.
861         */
862        public void setJpegQuality(int quality) {
863            set(KEY_JPEG_QUALITY, quality);
864        }
865
866        /**
867         * Returns the quality setting for the JPEG picture.
868         *
869         * @return the JPEG picture quality setting.
870         */
871        public int getJpegQuality() {
872            return getInt(KEY_JPEG_QUALITY);
873        }
874
875        /**
876         * Sets the rate at which preview frames are received.
877         *
878         * @param fps the frame rate (frames per second)
879         */
880        public void setPreviewFrameRate(int fps) {
881            set(KEY_PREVIEW_FRAME_RATE, fps);
882        }
883
884        /**
885         * Returns the setting for the rate at which preview frames
886         * are received.
887         *
888         * @return the frame rate setting (frames per second)
889         */
890        public int getPreviewFrameRate() {
891            return getInt(KEY_PREVIEW_FRAME_RATE);
892        }
893
894        /**
895         * Gets the supported preview frame rates.
896         *
897         * @return a List of Integer objects (preview frame rates). null if
898         *         preview frame rate setting is not supported.
899         */
900        public List<Integer> getSupportedPreviewFrameRates() {
901            String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX);
902            return splitInt(str);
903        }
904
905        /**
906         * Sets the image format for preview pictures.
907         * <p>If this is never called, the default format will be
908         * {@link android.graphics.PixelFormat#YCbCr_420_SP}, which
909         * uses the NV21 encoding format.</p>
910         *
911         * @param pixel_format the desired preview picture format, defined
912         *   by one of the {@link android.graphics.PixelFormat} constants.
913         *   (E.g., <var>PixelFormat.YCbCr_420_SP</var> (default),
914         *                      <var>PixelFormat.RGB_565</var>, or
915         *                      <var>PixelFormat.JPEG</var>)
916         * @see android.graphics.PixelFormat
917         */
918        public void setPreviewFormat(int pixel_format) {
919            String s = cameraFormatForPixelFormat(pixel_format);
920            if (s == null) {
921                throw new IllegalArgumentException(
922                        "Invalid pixel_format=" + pixel_format);
923            }
924
925            set(KEY_PREVIEW_FORMAT, s);
926        }
927
928        /**
929         * Returns the image format for preview pictures got from
930         * {@link PreviewCallback}.
931         *
932         * @return the {@link android.graphics.PixelFormat} int representing
933         *         the preview picture format.
934         */
935        public int getPreviewFormat() {
936            return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT));
937        }
938
939        /**
940         * Gets the supported preview formats.
941         *
942         * @return a List of Integer objects. null if preview format setting is
943         *         not supported.
944         */
945        public List<Integer> getSupportedPreviewFormats() {
946            String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX);
947            return splitInt(str);
948        }
949
950        /**
951         * Sets the dimensions for pictures.
952         *
953         * @param width  the width for pictures, in pixels
954         * @param height the height for pictures, in pixels
955         */
956        public void setPictureSize(int width, int height) {
957            String v = Integer.toString(width) + "x" + Integer.toString(height);
958            set(KEY_PICTURE_SIZE, v);
959        }
960
961        /**
962         * Returns the dimension setting for pictures.
963         *
964         * @return a Size object with the height and width setting
965         *          for pictures
966         */
967        public Size getPictureSize() {
968            String pair = get(KEY_PICTURE_SIZE);
969            return strToSize(pair);
970        }
971
972        /**
973         * Gets the supported picture sizes.
974         *
975         * @return a List of Size objects. null if picture size setting is not
976         *         supported.
977         */
978        public List<Size> getSupportedPictureSizes() {
979            String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX);
980            return splitSize(str);
981        }
982
983        /**
984         * Sets the image format for pictures.
985         *
986         * @param pixel_format the desired picture format
987         *                     (<var>PixelFormat.YCbCr_420_SP (NV21)</var>,
988         *                      <var>PixelFormat.RGB_565</var>, or
989         *                      <var>PixelFormat.JPEG</var>)
990         * @see android.graphics.PixelFormat
991         */
992        public void setPictureFormat(int pixel_format) {
993            String s = cameraFormatForPixelFormat(pixel_format);
994            if (s == null) {
995                throw new IllegalArgumentException(
996                        "Invalid pixel_format=" + pixel_format);
997            }
998
999            set(KEY_PICTURE_FORMAT, s);
1000        }
1001
1002        /**
1003         * Returns the image format for pictures.
1004         *
1005         * @return the PixelFormat int representing the picture format
1006         */
1007        public int getPictureFormat() {
1008            return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT));
1009        }
1010
1011        /**
1012         * Gets the supported picture formats.
1013         *
1014         * @return a List of Integer objects (values are PixelFormat.XXX). null
1015         *         if picture setting is not supported.
1016         */
1017        public List<Integer> getSupportedPictureFormats() {
1018            String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX);
1019            return splitInt(str);
1020        }
1021
1022        private String cameraFormatForPixelFormat(int pixel_format) {
1023            switch(pixel_format) {
1024            case PixelFormat.YCbCr_422_SP: return PIXEL_FORMAT_YUV422SP;
1025            case PixelFormat.YCbCr_420_SP: return PIXEL_FORMAT_YUV420SP;
1026            case PixelFormat.RGB_565:      return PIXEL_FORMAT_RGB565;
1027            case PixelFormat.JPEG:         return PIXEL_FORMAT_JPEG;
1028            default:                       return null;
1029            }
1030        }
1031
1032        private int pixelFormatForCameraFormat(String format) {
1033            if (format == null)
1034                return PixelFormat.UNKNOWN;
1035
1036            if (format.equals(PIXEL_FORMAT_YUV422SP))
1037                return PixelFormat.YCbCr_422_SP;
1038
1039            if (format.equals(PIXEL_FORMAT_YUV420SP))
1040                return PixelFormat.YCbCr_420_SP;
1041
1042            if (format.equals(PIXEL_FORMAT_RGB565))
1043                return PixelFormat.RGB_565;
1044
1045            if (format.equals(PIXEL_FORMAT_JPEG))
1046                return PixelFormat.JPEG;
1047
1048            return PixelFormat.UNKNOWN;
1049        }
1050
1051        /**
1052         * Sets the orientation of the device in degrees, which instructs the
1053         * camera driver to rotate the picture and thumbnail, in order to match
1054         * what the user sees from the viewfinder. For example, suppose the
1055         * natural position of the device is landscape. If the user takes a
1056         * picture in landscape mode in 2048x1536 resolution, the rotation
1057         * should be set to 0. If the user rotates the phone 90 degrees
1058         * clockwise, the rotation should be set to 90. Applications can use
1059         * {@link android.view.OrientationEventListener} to set this parameter.
1060         *
1061         * Since the picture is rotated, the orientation in the EXIF header is
1062         * missing or always 1 (row #0 is top and column #0 is left side).
1063         *
1064         * @param rotation The orientation of the device in degrees. Rotation
1065         *                 can only be 0, 90, 180 or 270.
1066         * @throws IllegalArgumentException if rotation value is invalid.
1067         * @see android.view.OrientationEventListener
1068         */
1069        public void setRotation(int rotation) {
1070            if (rotation == 0 || rotation == 90 || rotation == 180
1071                    || rotation == 270) {
1072                set(KEY_ROTATION, Integer.toString(rotation));
1073            } else {
1074                throw new IllegalArgumentException(
1075                        "Invalid rotation=" + rotation);
1076            }
1077        }
1078
1079        /**
1080         * Sets GPS latitude coordinate. This will be stored in JPEG EXIF
1081         * header.
1082         *
1083         * @param latitude GPS latitude coordinate.
1084         */
1085        public void setGpsLatitude(double latitude) {
1086            set(KEY_GPS_LATITUDE, Double.toString(latitude));
1087        }
1088
1089        /**
1090         * Sets GPS longitude coordinate. This will be stored in JPEG EXIF
1091         * header.
1092         *
1093         * @param longitude GPS longitude coordinate.
1094         */
1095        public void setGpsLongitude(double longitude) {
1096            set(KEY_GPS_LONGITUDE, Double.toString(longitude));
1097        }
1098
1099        /**
1100         * Sets GPS altitude. This will be stored in JPEG EXIF header.
1101         *
1102         * @param altitude GPS altitude in meters.
1103         */
1104        public void setGpsAltitude(double altitude) {
1105            set(KEY_GPS_ALTITUDE, Double.toString(altitude));
1106        }
1107
1108        /**
1109         * Sets GPS timestamp. This will be stored in JPEG EXIF header.
1110         *
1111         * @param timestamp GPS timestamp (UTC in seconds since January 1,
1112         *                  1970).
1113         */
1114        public void setGpsTimestamp(long timestamp) {
1115            set(KEY_GPS_TIMESTAMP, Long.toString(timestamp));
1116        }
1117
1118        /**
1119         * Removes GPS latitude, longitude, altitude, and timestamp from the
1120         * parameters.
1121         */
1122        public void removeGpsData() {
1123            remove(KEY_GPS_LATITUDE);
1124            remove(KEY_GPS_LONGITUDE);
1125            remove(KEY_GPS_ALTITUDE);
1126            remove(KEY_GPS_TIMESTAMP);
1127        }
1128
1129        /**
1130         * Gets the current white balance setting.
1131         *
1132         * @return one of WHITE_BALANCE_XXX string constant. null if white
1133         *         balance setting is not supported.
1134         */
1135        public String getWhiteBalance() {
1136            return get(KEY_WHITE_BALANCE);
1137        }
1138
1139        /**
1140         * Sets the white balance.
1141         *
1142         * @param value WHITE_BALANCE_XXX string constant.
1143         */
1144        public void setWhiteBalance(String value) {
1145            set(KEY_WHITE_BALANCE, value);
1146        }
1147
1148        /**
1149         * Gets the supported white balance.
1150         *
1151         * @return a List of WHITE_BALANCE_XXX string constants. null if white
1152         *         balance setting is not supported.
1153         */
1154        public List<String> getSupportedWhiteBalance() {
1155            String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX);
1156            return split(str);
1157        }
1158
1159        /**
1160         * Gets the current color effect setting.
1161         *
1162         * @return one of EFFECT_XXX string constant. null if color effect
1163         *         setting is not supported.
1164         */
1165        public String getColorEffect() {
1166            return get(KEY_EFFECT);
1167        }
1168
1169        /**
1170         * Sets the current color effect setting.
1171         *
1172         * @param value EFFECT_XXX string constants.
1173         */
1174        public void setColorEffect(String value) {
1175            set(KEY_EFFECT, value);
1176        }
1177
1178        /**
1179         * Gets the supported color effects.
1180         *
1181         * @return a List of EFFECT_XXX string constants. null if color effect
1182         *         setting is not supported.
1183         */
1184        public List<String> getSupportedColorEffects() {
1185            String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX);
1186            return split(str);
1187        }
1188
1189
1190        /**
1191         * Gets the current antibanding setting.
1192         *
1193         * @return one of ANTIBANDING_XXX string constant. null if antibanding
1194         *         setting is not supported.
1195         */
1196        public String getAntibanding() {
1197            return get(KEY_ANTIBANDING);
1198        }
1199
1200        /**
1201         * Sets the antibanding.
1202         *
1203         * @param antibanding ANTIBANDING_XXX string constant.
1204         */
1205        public void setAntibanding(String antibanding) {
1206            set(KEY_ANTIBANDING, antibanding);
1207        }
1208
1209        /**
1210         * Gets the supported antibanding values.
1211         *
1212         * @return a List of ANTIBANDING_XXX string constants. null if
1213         *         antibanding setting is not supported.
1214         */
1215        public List<String> getSupportedAntibanding() {
1216            String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX);
1217            return split(str);
1218        }
1219
1220        /**
1221         * Gets the current scene mode setting.
1222         *
1223         * @return one of SCENE_MODE_XXX string constant. null if scene mode
1224         *         setting is not supported.
1225         */
1226        public String getSceneMode() {
1227            return get(KEY_SCENE_MODE);
1228        }
1229
1230        /**
1231         * Sets the scene mode.
1232         *
1233         * @param value SCENE_MODE_XXX string constants.
1234         */
1235        public void setSceneMode(String value) {
1236            set(KEY_SCENE_MODE, value);
1237        }
1238
1239        /**
1240         * Gets the supported scene modes.
1241         *
1242         * @return a List of SCENE_MODE_XXX string constant. null if scene mode
1243         *         setting is not supported.
1244         */
1245        public List<String> getSupportedSceneModes() {
1246            String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX);
1247            return split(str);
1248        }
1249
1250        /**
1251         * Gets the current flash mode setting.
1252         *
1253         * @return one of FLASH_MODE_XXX string constant. null if flash mode
1254         *         setting is not supported.
1255         */
1256        public String getFlashMode() {
1257            return get(KEY_FLASH_MODE);
1258        }
1259
1260        /**
1261         * Sets the flash mode.
1262         *
1263         * @param value FLASH_MODE_XXX string constants.
1264         */
1265        public void setFlashMode(String value) {
1266            set(KEY_FLASH_MODE, value);
1267        }
1268
1269        /**
1270         * Gets the supported flash modes.
1271         *
1272         * @return a List of FLASH_MODE_XXX string constants. null if flash mode
1273         *         setting is not supported.
1274         */
1275        public List<String> getSupportedFlashModes() {
1276            String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX);
1277            return split(str);
1278        }
1279
1280        // Splits a comma delimited string to an ArrayList of String.
1281        // Return null if the passing string is null or the size is 0.
1282        private ArrayList<String> split(String str) {
1283            if (str == null) return null;
1284
1285            // Use StringTokenizer because it is faster than split.
1286            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1287            ArrayList<String> substrings = new ArrayList<String>();
1288            while (tokenizer.hasMoreElements()) {
1289                substrings.add(tokenizer.nextToken());
1290            }
1291            return substrings;
1292        }
1293
1294        // Splits a comma delimited string to an ArrayList of Integer.
1295        // Return null if the passing string is null or the size is 0.
1296        private ArrayList<Integer> splitInt(String str) {
1297            if (str == null) return null;
1298
1299            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1300            ArrayList<Integer> substrings = new ArrayList<Integer>();
1301            while (tokenizer.hasMoreElements()) {
1302                String token = tokenizer.nextToken();
1303                substrings.add(Integer.parseInt(token));
1304            }
1305            if (substrings.size() == 0) return null;
1306            return substrings;
1307        }
1308
1309        // Splits a comma delimited string to an ArrayList of Size.
1310        // Return null if the passing string is null or the size is 0.
1311        private ArrayList<Size> splitSize(String str) {
1312            if (str == null) return null;
1313
1314            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1315            ArrayList<Size> sizeList = new ArrayList<Size>();
1316            while (tokenizer.hasMoreElements()) {
1317                Size size = strToSize(tokenizer.nextToken());
1318                if (size != null) sizeList.add(size);
1319            }
1320            if (sizeList.size() == 0) return null;
1321            return sizeList;
1322        }
1323
1324        // Parses a string (ex: "480x320") to Size object.
1325        // Return null if the passing string is null.
1326        private Size strToSize(String str) {
1327            if (str == null) return null;
1328
1329            int pos = str.indexOf('x');
1330            if (pos != -1) {
1331                String width = str.substring(0, pos);
1332                String height = str.substring(pos + 1);
1333                return new Size(Integer.parseInt(width),
1334                                Integer.parseInt(height));
1335            }
1336            Log.e(TAG, "Invalid size parameter string=" + str);
1337            return null;
1338        }
1339    };
1340}
1341
1342
1343