Camera.java revision 46ad796186bdca8bac75607340aa0fac0c34a9d8
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     * Cancels auto-focus function. If the auto-focus is still in progress,
387     * this function will cancel it. Whether the auto-focus is in progress
388     * or not, this function will return the focus position to the default.
389     * If the camera does not support auto-focus, this is a no-op.
390     */
391    public final void cancelAutoFocus()
392    {
393        mAutoFocusCallback = null;
394        native_cancelAutoFocus();
395    }
396    private native final void native_cancelAutoFocus();
397
398    /**
399     * An interface which contains a callback for the shutter closing after taking a picture.
400     */
401    public interface ShutterCallback
402    {
403        /**
404         * Can be used to play a shutter sound as soon as the image has been captured, but before
405         * the data is available.
406         */
407        void onShutter();
408    }
409
410    /**
411     * Handles the callback for when a picture is taken.
412     */
413    public interface PictureCallback {
414        /**
415         * Callback for when a picture is taken.
416         *
417         * @param data   a byte array of the picture data
418         * @param camera the Camera service object
419         */
420        void onPictureTaken(byte[] data, Camera camera);
421    };
422
423    /**
424     * Triggers an asynchronous image capture. The camera service will initiate
425     * a series of callbacks to the application as the image capture progresses.
426     * The shutter callback occurs after the image is captured. This can be used
427     * to trigger a sound to let the user know that image has been captured. The
428     * raw callback occurs when the raw image data is available (NOTE: the data
429     * may be null if the hardware does not have enough memory to make a copy).
430     * The jpeg callback occurs when the compressed image is available. If the
431     * application does not need a particular callback, a null can be passed
432     * instead of a callback method.
433     *
434     * @param shutter   callback after the image is captured, may be null
435     * @param raw       callback with raw image data, may be null
436     * @param jpeg      callback with jpeg image data, may be null
437     */
438    public final void takePicture(ShutterCallback shutter, PictureCallback raw,
439            PictureCallback jpeg) {
440        takePicture(shutter, raw, null, jpeg);
441    }
442    private native final void native_takePicture();
443
444    /**
445     * Triggers an asynchronous image capture. The camera service will initiate
446     * a series of callbacks to the application as the image capture progresses.
447     * The shutter callback occurs after the image is captured. This can be used
448     * to trigger a sound to let the user know that image has been captured. The
449     * raw callback occurs when the raw image data is available (NOTE: the data
450     * may be null if the hardware does not have enough memory to make a copy).
451     * The postview callback occurs when a scaled, fully processed postview
452     * image is available (NOTE: not all hardware supports this). The jpeg
453     * callback occurs when the compressed image is available. If the
454     * application does not need a particular callback, a null can be passed
455     * instead of a callback method.
456     *
457     * @param shutter   callback after the image is captured, may be null
458     * @param raw       callback with raw image data, may be null
459     * @param postview  callback with postview image data, may be null
460     * @param jpeg      callback with jpeg image data, may be null
461     */
462    public final void takePicture(ShutterCallback shutter, PictureCallback raw,
463            PictureCallback postview, PictureCallback jpeg) {
464        mShutterCallback = shutter;
465        mRawImageCallback = raw;
466        mPostviewCallback = postview;
467        mJpegCallback = jpeg;
468        native_takePicture();
469    }
470
471    /**
472     * Handles the zoom callback.
473     */
474    public interface ZoomCallback
475    {
476        /**
477         * Callback for zoom updates
478         * @param zoomLevel   new zoom level in 1/1000 increments,
479         * e.g. a zoom of 3.2x is stored as 3200. Accuracy of the
480         * value is dependent on the hardware implementation. Not
481         * all devices will generate this callback.
482         * @param camera  the Camera service object
483         */
484        void onZoomUpdate(int zoomLevel, Camera camera);
485    };
486
487    /**
488     * Registers a callback to be invoked when the zoom
489     * level is updated by the camera driver.
490     * @param cb the callback to run
491     */
492    public final void setZoomCallback(ZoomCallback cb)
493    {
494        mZoomCallback = cb;
495    }
496
497    // These match the enum in include/ui/Camera.h
498    /** Unspecified camerar error.  @see #ErrorCallback */
499    public static final int CAMERA_ERROR_UNKNOWN = 1;
500    /** Media server died. In this case, the application must release the
501     * Camera object and instantiate a new one. @see #ErrorCallback */
502    public static final int CAMERA_ERROR_SERVER_DIED = 100;
503
504    /**
505     * Handles the camera error callback.
506     */
507    public interface ErrorCallback
508    {
509        /**
510         * Callback for camera errors.
511         * @param error   error code:
512         * <ul>
513         * <li>{@link #CAMERA_ERROR_UNKNOWN}
514         * <li>{@link #CAMERA_ERROR_SERVER_DIED}
515         * </ul>
516         * @param camera  the Camera service object
517         */
518        void onError(int error, Camera camera);
519    };
520
521    /**
522     * Registers a callback to be invoked when an error occurs.
523     * @param cb the callback to run
524     */
525    public final void setErrorCallback(ErrorCallback cb)
526    {
527        mErrorCallback = cb;
528    }
529
530    private native final void native_setParameters(String params);
531    private native final String native_getParameters();
532
533    /**
534     * Sets the Parameters for pictures from this Camera service.
535     *
536     * @param params the Parameters to use for this Camera service
537     */
538    public void setParameters(Parameters params) {
539        native_setParameters(params.flatten());
540    }
541
542    /**
543     * Returns the picture Parameters for this Camera service.
544     */
545    public Parameters getParameters() {
546        Parameters p = new Parameters();
547        String s = native_getParameters();
548        p.unflatten(s);
549        return p;
550    }
551
552    /**
553     * Handles the picture size (dimensions).
554     */
555    public class Size {
556        /**
557         * Sets the dimensions for pictures.
558         *
559         * @param w the photo width (pixels)
560         * @param h the photo height (pixels)
561         */
562        public Size(int w, int h) {
563            width = w;
564            height = h;
565        }
566        /** width of the picture */
567        public int width;
568        /** height of the picture */
569        public int height;
570    };
571
572    /**
573     * Handles the parameters for pictures created by a Camera service.
574     *
575     * <p>To make camera parameters take effect, applications have to call
576     * Camera.setParameters. For example, after setWhiteBalance is called, white
577     * balance is not changed until Camera.setParameters() is called.
578     *
579     * <p>Different devices may have different camera capabilities, such as
580     * picture size or flash modes. The application should query the camera
581     * capabilities before setting parameters. For example, the application
582     * should call getSupportedColorEffects before calling setEffect. If the
583     * camera does not support color effects, getSupportedColorEffects will
584     * return null.
585     */
586    public class Parameters {
587        // Parameter keys to communicate with the camera driver.
588        private static final String KEY_PREVIEW_SIZE = "preview-size";
589        private static final String KEY_PREVIEW_FORMAT = "preview-format";
590        private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate";
591        private static final String KEY_PICTURE_SIZE = "picture-size";
592        private static final String KEY_PICTURE_FORMAT = "picture-format";
593        private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width";
594        private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height";
595        private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality";
596        private static final String KEY_JPEG_QUALITY = "jpeg-quality";
597        private static final String KEY_ROTATION = "rotation";
598        private static final String KEY_GPS_LATITUDE = "gps-latitude";
599        private static final String KEY_GPS_LONGITUDE = "gps-longitude";
600        private static final String KEY_GPS_ALTITUDE = "gps-altitude";
601        private static final String KEY_GPS_TIMESTAMP = "gps-timestamp";
602        private static final String KEY_WHITE_BALANCE = "whitebalance";
603        private static final String KEY_EFFECT = "effect";
604        private static final String KEY_ANTIBANDING = "antibanding";
605        private static final String KEY_SCENE_MODE = "scene-mode";
606        private static final String KEY_FLASH_MODE = "flash-mode";
607        // Parameter key suffix for supported values.
608        private static final String SUPPORTED_VALUES_SUFFIX = "-values";
609
610        // Values for white balance settings.
611        public static final String WHITE_BALANCE_AUTO = "auto";
612        public static final String WHITE_BALANCE_INCANDESCENT = "incandescent";
613        public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent";
614        public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent";
615        public static final String WHITE_BALANCE_DAYLIGHT = "daylight";
616        public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight";
617        public static final String WHITE_BALANCE_TWILIGHT = "twilight";
618        public static final String WHITE_BALANCE_SHADE = "shade";
619
620        // Values for color effect settings.
621        public static final String EFFECT_NONE = "none";
622        public static final String EFFECT_MONO = "mono";
623        public static final String EFFECT_NEGATIVE = "negative";
624        public static final String EFFECT_SOLARIZE = "solarize";
625        public static final String EFFECT_SEPIA = "sepia";
626        public static final String EFFECT_POSTERIZE = "posterize";
627        public static final String EFFECT_WHITEBOARD = "whiteboard";
628        public static final String EFFECT_BLACKBOARD = "blackboard";
629        public static final String EFFECT_AQUA = "aqua";
630
631        // Values for antibanding settings.
632        public static final String ANTIBANDING_AUTO = "auto";
633        public static final String ANTIBANDING_50HZ = "50hz";
634        public static final String ANTIBANDING_60HZ = "60hz";
635        public static final String ANTIBANDING_OFF = "off";
636
637        // Values for flash mode settings.
638        /**
639         * Flash will not be fired.
640         */
641        public static final String FLASH_MODE_OFF = "off";
642        /**
643         * Flash will be fired automatically when required. The timing is
644         * decided by camera driver.
645         */
646        public static final String FLASH_MODE_AUTO = "auto";
647        /**
648         * Flash will always be fired. The timing is decided by camera driver.
649         */
650        public static final String FLASH_MODE_ON = "on";
651        /**
652         * Flash will be fired in red-eye reduction mode.
653         */
654        public static final String FLASH_MODE_RED_EYE = "red-eye";
655
656        // Values for scene mode settings.
657        public static final String SCENE_MODE_AUTO = "auto";
658        public static final String SCENE_MODE_ACTION = "action";
659        public static final String SCENE_MODE_PORTRAIT = "portrait";
660        public static final String SCENE_MODE_LANDSCAPE = "landscape";
661        public static final String SCENE_MODE_NIGHT = "night";
662        public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait";
663        public static final String SCENE_MODE_THEATRE = "theatre";
664        public static final String SCENE_MODE_BEACH = "beach";
665        public static final String SCENE_MODE_SNOW = "snow";
666        public static final String SCENE_MODE_SUNSET = "sunset";
667        public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto";
668        public static final String SCENE_MODE_FIREWORKS = "fireworks";
669        public static final String SCENE_MODE_SPORTS = "sports";
670        public static final String SCENE_MODE_PARTY = "party";
671        public static final String SCENE_MODE_CANDLELIGHT = "candlelight";
672
673        // Formats for setPreviewFormat and setPictureFormat.
674        private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp";
675        private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp";
676        private static final String PIXEL_FORMAT_RGB565 = "rgb565";
677        private static final String PIXEL_FORMAT_JPEG = "jpeg";
678
679        private HashMap<String, String> mMap;
680
681        private Parameters() {
682            mMap = new HashMap<String, String>();
683        }
684
685        /**
686         * Writes the current Parameters to the log.
687         * @hide
688         * @deprecated
689         */
690        public void dump() {
691            Log.e(TAG, "dump: size=" + mMap.size());
692            for (String k : mMap.keySet()) {
693                Log.e(TAG, "dump: " + k + "=" + mMap.get(k));
694            }
695        }
696
697        /**
698         * Creates a single string with all the parameters set in
699         * this Parameters object.
700         * <p>The {@link #unflatten(String)} method does the reverse.</p>
701         *
702         * @return a String with all values from this Parameters object, in
703         *         semi-colon delimited key-value pairs
704         */
705        public String flatten() {
706            StringBuilder flattened = new StringBuilder();
707            for (String k : mMap.keySet()) {
708                flattened.append(k);
709                flattened.append("=");
710                flattened.append(mMap.get(k));
711                flattened.append(";");
712            }
713            // chop off the extra semicolon at the end
714            flattened.deleteCharAt(flattened.length()-1);
715            return flattened.toString();
716        }
717
718        /**
719         * Takes a flattened string of parameters and adds each one to
720         * this Parameters object.
721         * <p>The {@link #flatten()} method does the reverse.</p>
722         *
723         * @param flattened a String of parameters (key-value paired) that
724         *                  are semi-colon delimited
725         */
726        public void unflatten(String flattened) {
727            mMap.clear();
728
729            StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
730            while (tokenizer.hasMoreElements()) {
731                String kv = tokenizer.nextToken();
732                int pos = kv.indexOf('=');
733                if (pos == -1) {
734                    continue;
735                }
736                String k = kv.substring(0, pos);
737                String v = kv.substring(pos + 1);
738                mMap.put(k, v);
739            }
740        }
741
742        public void remove(String key) {
743            mMap.remove(key);
744        }
745
746        /**
747         * Sets a String parameter.
748         *
749         * @param key   the key name for the parameter
750         * @param value the String value of the parameter
751         */
752        public void set(String key, String value) {
753            if (key.indexOf('=') != -1 || key.indexOf(';') != -1) {
754                Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ;)");
755                return;
756            }
757            if (value.indexOf('=') != -1 || value.indexOf(';') != -1) {
758                Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ;)");
759                return;
760            }
761
762            mMap.put(key, value);
763        }
764
765        /**
766         * Sets an integer parameter.
767         *
768         * @param key   the key name for the parameter
769         * @param value the int value of the parameter
770         */
771        public void set(String key, int value) {
772            mMap.put(key, Integer.toString(value));
773        }
774
775        /**
776         * Returns the value of a String parameter.
777         *
778         * @param key the key name for the parameter
779         * @return the String value of the parameter
780         */
781        public String get(String key) {
782            return mMap.get(key);
783        }
784
785        /**
786         * Returns the value of an integer parameter.
787         *
788         * @param key the key name for the parameter
789         * @return the int value of the parameter
790         */
791        public int getInt(String key) {
792            return Integer.parseInt(mMap.get(key));
793        }
794
795        /**
796         * Sets the dimensions for preview pictures.
797         *
798         * @param width  the width of the pictures, in pixels
799         * @param height the height of the pictures, in pixels
800         */
801        public void setPreviewSize(int width, int height) {
802            String v = Integer.toString(width) + "x" + Integer.toString(height);
803            set(KEY_PREVIEW_SIZE, v);
804        }
805
806        /**
807         * Returns the dimensions setting for preview pictures.
808         *
809         * @return a Size object with the height and width setting
810         *          for the preview picture
811         */
812        public Size getPreviewSize() {
813            String pair = get(KEY_PREVIEW_SIZE);
814            return strToSize(pair);
815        }
816
817        /**
818         * Gets the supported preview sizes.
819         *
820         * @return a List of Size object. null if preview size setting is not
821         *         supported.
822         */
823        public List<Size> getSupportedPreviewSizes() {
824            String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX);
825            return splitSize(str);
826        }
827
828        /**
829         * Sets the dimensions for EXIF thumbnail in Jpeg picture.
830         *
831         * @param width  the width of the thumbnail, in pixels
832         * @param height the height of the thumbnail, in pixels
833         */
834        public void setJpegThumbnailSize(int width, int height) {
835            set(KEY_JPEG_THUMBNAIL_WIDTH, width);
836            set(KEY_JPEG_THUMBNAIL_HEIGHT, height);
837        }
838
839        /**
840         * Returns the dimensions for EXIF thumbnail in Jpeg picture.
841         *
842         * @return a Size object with the height and width setting for the EXIF
843         *         thumbnails
844         */
845        public Size getJpegThumbnailSize() {
846            return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH),
847                            getInt(KEY_JPEG_THUMBNAIL_HEIGHT));
848        }
849
850        /**
851         * Sets the quality of the EXIF thumbnail in Jpeg picture.
852         *
853         * @param quality the JPEG quality of the EXIF thumbnail. The range is 1
854         *                to 100, with 100 being the best.
855         */
856        public void setJpegThumbnailQuality(int quality) {
857            set(KEY_JPEG_THUMBNAIL_QUALITY, quality);
858        }
859
860        /**
861         * Returns the quality setting for the EXIF thumbnail in Jpeg picture.
862         *
863         * @return the JPEG quality setting of the EXIF thumbnail.
864         */
865        public int getJpegThumbnailQuality() {
866            return getInt(KEY_JPEG_THUMBNAIL_QUALITY);
867        }
868
869        /**
870         * Sets Jpeg quality of captured picture.
871         *
872         * @param quality the JPEG quality of captured picture. The range is 1
873         *                to 100, with 100 being the best.
874         */
875        public void setJpegQuality(int quality) {
876            set(KEY_JPEG_QUALITY, quality);
877        }
878
879        /**
880         * Returns the quality setting for the JPEG picture.
881         *
882         * @return the JPEG picture quality setting.
883         */
884        public int getJpegQuality() {
885            return getInt(KEY_JPEG_QUALITY);
886        }
887
888        /**
889         * Sets the rate at which preview frames are received.
890         *
891         * @param fps the frame rate (frames per second)
892         */
893        public void setPreviewFrameRate(int fps) {
894            set(KEY_PREVIEW_FRAME_RATE, fps);
895        }
896
897        /**
898         * Returns the setting for the rate at which preview frames
899         * are received.
900         *
901         * @return the frame rate setting (frames per second)
902         */
903        public int getPreviewFrameRate() {
904            return getInt(KEY_PREVIEW_FRAME_RATE);
905        }
906
907        /**
908         * Gets the supported preview frame rates.
909         *
910         * @return a List of Integer objects (preview frame rates). null if
911         *         preview frame rate setting is not supported.
912         */
913        public List<Integer> getSupportedPreviewFrameRates() {
914            String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX);
915            return splitInt(str);
916        }
917
918        /**
919         * Sets the image format for preview pictures.
920         * <p>If this is never called, the default format will be
921         * {@link android.graphics.PixelFormat#YCbCr_420_SP}, which
922         * uses the NV21 encoding format.</p>
923         *
924         * @param pixel_format the desired preview picture format, defined
925         *   by one of the {@link android.graphics.PixelFormat} constants.
926         *   (E.g., <var>PixelFormat.YCbCr_420_SP</var> (default),
927         *                      <var>PixelFormat.RGB_565</var>, or
928         *                      <var>PixelFormat.JPEG</var>)
929         * @see android.graphics.PixelFormat
930         */
931        public void setPreviewFormat(int pixel_format) {
932            String s = cameraFormatForPixelFormat(pixel_format);
933            if (s == null) {
934                throw new IllegalArgumentException(
935                        "Invalid pixel_format=" + pixel_format);
936            }
937
938            set(KEY_PREVIEW_FORMAT, s);
939        }
940
941        /**
942         * Returns the image format for preview pictures got from
943         * {@link PreviewCallback}.
944         *
945         * @return the {@link android.graphics.PixelFormat} int representing
946         *         the preview picture format.
947         */
948        public int getPreviewFormat() {
949            return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT));
950        }
951
952        /**
953         * Gets the supported preview formats.
954         *
955         * @return a List of Integer objects. null if preview format setting is
956         *         not supported.
957         */
958        public List<Integer> getSupportedPreviewFormats() {
959            String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX);
960            return splitInt(str);
961        }
962
963        /**
964         * Sets the dimensions for pictures.
965         *
966         * @param width  the width for pictures, in pixels
967         * @param height the height for pictures, in pixels
968         */
969        public void setPictureSize(int width, int height) {
970            String v = Integer.toString(width) + "x" + Integer.toString(height);
971            set(KEY_PICTURE_SIZE, v);
972        }
973
974        /**
975         * Returns the dimension setting for pictures.
976         *
977         * @return a Size object with the height and width setting
978         *          for pictures
979         */
980        public Size getPictureSize() {
981            String pair = get(KEY_PICTURE_SIZE);
982            return strToSize(pair);
983        }
984
985        /**
986         * Gets the supported picture sizes.
987         *
988         * @return a List of Size objects. null if picture size setting is not
989         *         supported.
990         */
991        public List<Size> getSupportedPictureSizes() {
992            String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX);
993            return splitSize(str);
994        }
995
996        /**
997         * Sets the image format for pictures.
998         *
999         * @param pixel_format the desired picture format
1000         *                     (<var>PixelFormat.YCbCr_420_SP (NV21)</var>,
1001         *                      <var>PixelFormat.RGB_565</var>, or
1002         *                      <var>PixelFormat.JPEG</var>)
1003         * @see android.graphics.PixelFormat
1004         */
1005        public void setPictureFormat(int pixel_format) {
1006            String s = cameraFormatForPixelFormat(pixel_format);
1007            if (s == null) {
1008                throw new IllegalArgumentException(
1009                        "Invalid pixel_format=" + pixel_format);
1010            }
1011
1012            set(KEY_PICTURE_FORMAT, s);
1013        }
1014
1015        /**
1016         * Returns the image format for pictures.
1017         *
1018         * @return the PixelFormat int representing the picture format
1019         */
1020        public int getPictureFormat() {
1021            return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT));
1022        }
1023
1024        /**
1025         * Gets the supported picture formats.
1026         *
1027         * @return a List of Integer objects (values are PixelFormat.XXX). null
1028         *         if picture setting is not supported.
1029         */
1030        public List<Integer> getSupportedPictureFormats() {
1031            String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX);
1032            return splitInt(str);
1033        }
1034
1035        private String cameraFormatForPixelFormat(int pixel_format) {
1036            switch(pixel_format) {
1037            case PixelFormat.YCbCr_422_SP: return PIXEL_FORMAT_YUV422SP;
1038            case PixelFormat.YCbCr_420_SP: return PIXEL_FORMAT_YUV420SP;
1039            case PixelFormat.RGB_565:      return PIXEL_FORMAT_RGB565;
1040            case PixelFormat.JPEG:         return PIXEL_FORMAT_JPEG;
1041            default:                       return null;
1042            }
1043        }
1044
1045        private int pixelFormatForCameraFormat(String format) {
1046            if (format == null)
1047                return PixelFormat.UNKNOWN;
1048
1049            if (format.equals(PIXEL_FORMAT_YUV422SP))
1050                return PixelFormat.YCbCr_422_SP;
1051
1052            if (format.equals(PIXEL_FORMAT_YUV420SP))
1053                return PixelFormat.YCbCr_420_SP;
1054
1055            if (format.equals(PIXEL_FORMAT_RGB565))
1056                return PixelFormat.RGB_565;
1057
1058            if (format.equals(PIXEL_FORMAT_JPEG))
1059                return PixelFormat.JPEG;
1060
1061            return PixelFormat.UNKNOWN;
1062        }
1063
1064        /**
1065         * Sets the orientation of the device in degrees, which instructs the
1066         * camera driver to rotate the picture and thumbnail, in order to match
1067         * what the user sees from the viewfinder. For example, suppose the
1068         * natural position of the device is landscape. If the user takes a
1069         * picture in landscape mode in 2048x1536 resolution, the rotation
1070         * should be set to 0. If the user rotates the phone 90 degrees
1071         * clockwise, the rotation should be set to 90. Applications can use
1072         * {@link android.view.OrientationEventListener} to set this parameter.
1073         *
1074         * Since the picture is rotated, the orientation in the EXIF header is
1075         * missing or always 1 (row #0 is top and column #0 is left side).
1076         *
1077         * @param rotation The orientation of the device in degrees. Rotation
1078         *                 can only be 0, 90, 180 or 270.
1079         * @throws IllegalArgumentException if rotation value is invalid.
1080         * @see android.view.OrientationEventListener
1081         */
1082        public void setRotation(int rotation) {
1083            if (rotation == 0 || rotation == 90 || rotation == 180
1084                    || rotation == 270) {
1085                set(KEY_ROTATION, Integer.toString(rotation));
1086            } else {
1087                throw new IllegalArgumentException(
1088                        "Invalid rotation=" + rotation);
1089            }
1090        }
1091
1092        /**
1093         * Sets GPS latitude coordinate. This will be stored in JPEG EXIF
1094         * header.
1095         *
1096         * @param latitude GPS latitude coordinate.
1097         */
1098        public void setGpsLatitude(double latitude) {
1099            set(KEY_GPS_LATITUDE, Double.toString(latitude));
1100        }
1101
1102        /**
1103         * Sets GPS longitude coordinate. This will be stored in JPEG EXIF
1104         * header.
1105         *
1106         * @param longitude GPS longitude coordinate.
1107         */
1108        public void setGpsLongitude(double longitude) {
1109            set(KEY_GPS_LONGITUDE, Double.toString(longitude));
1110        }
1111
1112        /**
1113         * Sets GPS altitude. This will be stored in JPEG EXIF header.
1114         *
1115         * @param altitude GPS altitude in meters.
1116         */
1117        public void setGpsAltitude(double altitude) {
1118            set(KEY_GPS_ALTITUDE, Double.toString(altitude));
1119        }
1120
1121        /**
1122         * Sets GPS timestamp. This will be stored in JPEG EXIF header.
1123         *
1124         * @param timestamp GPS timestamp (UTC in seconds since January 1,
1125         *                  1970).
1126         */
1127        public void setGpsTimestamp(long timestamp) {
1128            set(KEY_GPS_TIMESTAMP, Long.toString(timestamp));
1129        }
1130
1131        /**
1132         * Removes GPS latitude, longitude, altitude, and timestamp from the
1133         * parameters.
1134         */
1135        public void removeGpsData() {
1136            remove(KEY_GPS_LATITUDE);
1137            remove(KEY_GPS_LONGITUDE);
1138            remove(KEY_GPS_ALTITUDE);
1139            remove(KEY_GPS_TIMESTAMP);
1140        }
1141
1142        /**
1143         * Gets the current white balance setting.
1144         *
1145         * @return one of WHITE_BALANCE_XXX string constant. null if white
1146         *         balance setting is not supported.
1147         */
1148        public String getWhiteBalance() {
1149            return get(KEY_WHITE_BALANCE);
1150        }
1151
1152        /**
1153         * Sets the white balance.
1154         *
1155         * @param value WHITE_BALANCE_XXX string constant.
1156         */
1157        public void setWhiteBalance(String value) {
1158            set(KEY_WHITE_BALANCE, value);
1159        }
1160
1161        /**
1162         * Gets the supported white balance.
1163         *
1164         * @return a List of WHITE_BALANCE_XXX string constants. null if white
1165         *         balance setting is not supported.
1166         */
1167        public List<String> getSupportedWhiteBalance() {
1168            String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX);
1169            return split(str);
1170        }
1171
1172        /**
1173         * Gets the current color effect setting.
1174         *
1175         * @return one of EFFECT_XXX string constant. null if color effect
1176         *         setting is not supported.
1177         */
1178        public String getColorEffect() {
1179            return get(KEY_EFFECT);
1180        }
1181
1182        /**
1183         * Sets the current color effect setting.
1184         *
1185         * @param value EFFECT_XXX string constants.
1186         */
1187        public void setColorEffect(String value) {
1188            set(KEY_EFFECT, value);
1189        }
1190
1191        /**
1192         * Gets the supported color effects.
1193         *
1194         * @return a List of EFFECT_XXX string constants. null if color effect
1195         *         setting is not supported.
1196         */
1197        public List<String> getSupportedColorEffects() {
1198            String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX);
1199            return split(str);
1200        }
1201
1202
1203        /**
1204         * Gets the current antibanding setting.
1205         *
1206         * @return one of ANTIBANDING_XXX string constant. null if antibanding
1207         *         setting is not supported.
1208         */
1209        public String getAntibanding() {
1210            return get(KEY_ANTIBANDING);
1211        }
1212
1213        /**
1214         * Sets the antibanding.
1215         *
1216         * @param antibanding ANTIBANDING_XXX string constant.
1217         */
1218        public void setAntibanding(String antibanding) {
1219            set(KEY_ANTIBANDING, antibanding);
1220        }
1221
1222        /**
1223         * Gets the supported antibanding values.
1224         *
1225         * @return a List of ANTIBANDING_XXX string constants. null if
1226         *         antibanding setting is not supported.
1227         */
1228        public List<String> getSupportedAntibanding() {
1229            String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX);
1230            return split(str);
1231        }
1232
1233        /**
1234         * Gets the current scene mode setting.
1235         *
1236         * @return one of SCENE_MODE_XXX string constant. null if scene mode
1237         *         setting is not supported.
1238         */
1239        public String getSceneMode() {
1240            return get(KEY_SCENE_MODE);
1241        }
1242
1243        /**
1244         * Sets the scene mode.
1245         *
1246         * @param value SCENE_MODE_XXX string constants.
1247         */
1248        public void setSceneMode(String value) {
1249            set(KEY_SCENE_MODE, value);
1250        }
1251
1252        /**
1253         * Gets the supported scene modes.
1254         *
1255         * @return a List of SCENE_MODE_XXX string constant. null if scene mode
1256         *         setting is not supported.
1257         */
1258        public List<String> getSupportedSceneModes() {
1259            String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX);
1260            return split(str);
1261        }
1262
1263        /**
1264         * Gets the current flash mode setting.
1265         *
1266         * @return one of FLASH_MODE_XXX string constant. null if flash mode
1267         *         setting is not supported.
1268         */
1269        public String getFlashMode() {
1270            return get(KEY_FLASH_MODE);
1271        }
1272
1273        /**
1274         * Sets the flash mode.
1275         *
1276         * @param value FLASH_MODE_XXX string constants.
1277         */
1278        public void setFlashMode(String value) {
1279            set(KEY_FLASH_MODE, value);
1280        }
1281
1282        /**
1283         * Gets the supported flash modes.
1284         *
1285         * @return a List of FLASH_MODE_XXX string constants. null if flash mode
1286         *         setting is not supported.
1287         */
1288        public List<String> getSupportedFlashModes() {
1289            String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX);
1290            return split(str);
1291        }
1292
1293        // Splits a comma delimited string to an ArrayList of String.
1294        // Return null if the passing string is null or the size is 0.
1295        private ArrayList<String> split(String str) {
1296            if (str == null) return null;
1297
1298            // Use StringTokenizer because it is faster than split.
1299            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1300            ArrayList<String> substrings = new ArrayList<String>();
1301            while (tokenizer.hasMoreElements()) {
1302                substrings.add(tokenizer.nextToken());
1303            }
1304            return substrings;
1305        }
1306
1307        // Splits a comma delimited string to an ArrayList of Integer.
1308        // Return null if the passing string is null or the size is 0.
1309        private ArrayList<Integer> splitInt(String str) {
1310            if (str == null) return null;
1311
1312            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1313            ArrayList<Integer> substrings = new ArrayList<Integer>();
1314            while (tokenizer.hasMoreElements()) {
1315                String token = tokenizer.nextToken();
1316                substrings.add(Integer.parseInt(token));
1317            }
1318            if (substrings.size() == 0) return null;
1319            return substrings;
1320        }
1321
1322        // Splits a comma delimited string to an ArrayList of Size.
1323        // Return null if the passing string is null or the size is 0.
1324        private ArrayList<Size> splitSize(String str) {
1325            if (str == null) return null;
1326
1327            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1328            ArrayList<Size> sizeList = new ArrayList<Size>();
1329            while (tokenizer.hasMoreElements()) {
1330                Size size = strToSize(tokenizer.nextToken());
1331                if (size != null) sizeList.add(size);
1332            }
1333            if (sizeList.size() == 0) return null;
1334            return sizeList;
1335        }
1336
1337        // Parses a string (ex: "480x320") to Size object.
1338        // Return null if the passing string is null.
1339        private Size strToSize(String str) {
1340            if (str == null) return null;
1341
1342            int pos = str.indexOf('x');
1343            if (pos != -1) {
1344                String width = str.substring(0, pos);
1345                String height = str.substring(pos + 1);
1346                return new Size(Integer.parseInt(width),
1347                                Integer.parseInt(height));
1348            }
1349            Log.e(TAG, "Invalid size parameter string=" + str);
1350            return null;
1351        }
1352    };
1353}
1354