Apparent fix for issue 383 / Moment + Android 2.1 issue
[zxing.git] / android / src / com / google / zxing / client / android / camera / CameraManager.java
1 /*
2  * Copyright (C) 2008 ZXing authors
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
17 package com.google.zxing.client.android.camera;
18
19 import android.content.Context;
20 import android.content.SharedPreferences;
21 import android.graphics.PixelFormat;
22 import android.graphics.Point;
23 import android.graphics.Rect;
24 import android.hardware.Camera;
25 import android.os.Build;
26 import android.os.Handler;
27 import android.preference.PreferenceManager;
28 import android.util.Log;
29 import android.view.SurfaceHolder;
30 import com.google.zxing.client.android.PlanarYUVLuminanceSource;
31 import com.google.zxing.client.android.PreferencesActivity;
32
33 import java.io.IOException;
34
35 /**
36  * This object wraps the Camera service object and expects to be the only one talking to it. The
37  * implementation encapsulates the steps needed to take preview-sized images, which are used for
38  * both preview and decoding.
39  *
40  * @author dswitkin@google.com (Daniel Switkin)
41  */
42 public final class CameraManager {
43
44   private static final String TAG = CameraManager.class.getSimpleName();
45
46   private static final int MIN_FRAME_WIDTH = 240;
47   private static final int MIN_FRAME_HEIGHT = 240;
48   private static final int MAX_FRAME_WIDTH = 480;
49   private static final int MAX_FRAME_HEIGHT = 360;
50
51   private static CameraManager cameraManager;
52
53   private final Context context;
54   private final CameraConfigurationManager configManager;
55   private Camera camera;
56   private Rect framingRect;
57   private Rect framingRectInPreview;
58   private boolean initialized;
59   private boolean previewing;
60   private final boolean useOneShotPreviewCallback;
61   /**
62    * Preview frames are delivered here, which we pass on to the registered handler. Make sure to
63    * clear the handler so it will only receive one message.
64    */
65   private final PreviewCallback previewCallback;
66   /** Autofocus callbacks arrive here, and are dispatched to the Handler which requested them. */
67   private final AutoFocusCallback autoFocusCallback;
68
69   /**
70    * Initializes this static object with the Context of the calling Activity.
71    *
72    * @param context The Activity which wants to use the camera.
73    */
74   public static void init(Context context) {
75     if (cameraManager == null) {
76       cameraManager = new CameraManager(context);
77     }
78   }
79
80   /**
81    * Gets the CameraManager singleton instance.
82    *
83    * @return A reference to the CameraManager singleton.
84    */
85   public static CameraManager get() {
86     return cameraManager;
87   }
88
89   private CameraManager(Context context) {
90
91     this.context = context;
92     this.configManager = new CameraConfigurationManager(context);
93
94     // Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older
95     // Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use
96     // the more efficient one shot callback, as the older one can swamp the system and cause it
97     // to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.
98     useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;
99
100     previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);
101     autoFocusCallback = new AutoFocusCallback(configManager);
102   }
103
104   /**
105    * Opens the camera driver and initializes the hardware parameters.
106    *
107    * @param holder The surface object which the camera will draw preview frames into.
108    * @throws IOException Indicates the camera driver failed to open.
109    */
110   public void openDriver(SurfaceHolder holder) throws IOException {
111     if (camera == null) {
112       camera = Camera.open();
113       if (camera == null) {
114         throw new IOException();
115       }
116       camera.setPreviewDisplay(holder);
117
118       if (!initialized) {
119         initialized = true;
120         configManager.initFromCameraParameters(camera);
121       }
122       configManager.setDesiredCameraParameters(camera);
123
124       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
125       if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {
126         FlashlightManager.enableFlashlight();
127       }
128     }
129   }
130
131   /**
132    * Closes the camera driver if still in use.
133    */
134   public void closeDriver() {
135     if (camera != null) {
136       FlashlightManager.disableFlashlight();
137       camera.release();
138       camera = null;
139     }
140   }
141
142   /**
143    * Asks the camera hardware to begin drawing preview frames to the screen.
144    */
145   public void startPreview() {
146     if (camera != null && !previewing) {
147       camera.startPreview();
148       previewing = true;
149     }
150   }
151
152   /**
153    * Tells the camera to stop drawing preview frames.
154    */
155   public void stopPreview() {
156     if (camera != null && previewing) {
157       if (!useOneShotPreviewCallback) {
158         camera.setPreviewCallback(null);
159       }
160       camera.stopPreview();
161       previewCallback.setHandler(null, 0);
162       autoFocusCallback.setHandler(null, 0);
163       previewing = false;
164     }
165   }
166
167   /**
168    * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
169    * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
170    * respectively.
171    *
172    * @param handler The handler to send the message to.
173    * @param message The what field of the message to be sent.
174    */
175   public void requestPreviewFrame(Handler handler, int message) {
176     if (camera != null && previewing) {
177       previewCallback.setHandler(handler, message);
178       if (useOneShotPreviewCallback) {
179         camera.setOneShotPreviewCallback(previewCallback);
180       } else {
181         camera.setPreviewCallback(previewCallback);
182       }
183     }
184   }
185
186   /**
187    * Asks the camera hardware to perform an autofocus.
188    *
189    * @param handler The Handler to notify when the autofocus completes.
190    * @param message The message to deliver.
191    */
192   public void requestAutoFocus(Handler handler, int message) {
193     if (camera != null && previewing) {
194       autoFocusCallback.setHandler(handler, message);
195       camera.autoFocus(autoFocusCallback);
196     }
197   }
198
199   /**
200    * Calculates the framing rect which the UI should draw to show the user where to place the
201    * barcode. This target helps with alignment as well as forces the user to hold the device
202    * far enough away to ensure the image will be in focus.
203    *
204    * @return The rectangle to draw on screen in window coordinates.
205    */
206   public Rect getFramingRect() {
207     Point screenResolution = configManager.getScreenResolution();
208     if (framingRect == null) {
209       if (camera == null) {
210         return null;
211       }
212       int width = screenResolution.x * 3 / 4;
213       if (width < MIN_FRAME_WIDTH) {
214         width = MIN_FRAME_WIDTH;
215       } else if (width > MAX_FRAME_WIDTH) {
216         width = MAX_FRAME_WIDTH;
217       }
218       int height = screenResolution.y * 3 / 4;
219       if (height < MIN_FRAME_HEIGHT) {
220         height = MIN_FRAME_HEIGHT;
221       } else if (height > MAX_FRAME_HEIGHT) {
222         height = MAX_FRAME_HEIGHT;
223       }
224       int leftOffset = (screenResolution.x - width) / 2;
225       int topOffset = (screenResolution.y - height) / 2;
226       framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
227       Log.v(TAG, "Calculated framing rect: " + framingRect);
228     }
229     return framingRect;
230   }
231
232   /**
233    * Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
234    * not UI / screen.
235    */
236   public Rect getFramingRectInPreview() {
237     if (framingRectInPreview == null) {
238       Rect rect = new Rect(getFramingRect());
239       Point cameraResolution = configManager.getCameraResolution();
240       Point screenResolution = configManager.getScreenResolution();
241       rect.left = rect.left * cameraResolution.x / screenResolution.x;
242       rect.right = rect.right * cameraResolution.x / screenResolution.x;
243       rect.top = rect.top * cameraResolution.y / screenResolution.y;
244       rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
245       framingRectInPreview = rect;
246     }
247     return framingRectInPreview;
248   }
249
250   /**
251    * Converts the result points from still resolution coordinates to screen coordinates.
252    *
253    * @param points The points returned by the Reader subclass through Result.getResultPoints().
254    * @return An array of Points scaled to the size of the framing rect and offset appropriately
255    *         so they can be drawn in screen coordinates.
256    */
257   /*
258   public Point[] convertResultPoints(ResultPoint[] points) {
259     Rect frame = getFramingRectInPreview();
260     int count = points.length;
261     Point[] output = new Point[count];
262     for (int x = 0; x < count; x++) {
263       output[x] = new Point();
264       output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
265       output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
266     }
267     return output;
268   }
269    */
270
271   /**
272    * A factory method to build the appropriate LuminanceSource object based on the format
273    * of the preview buffers, as described by Camera.Parameters.
274    *
275    * @param data A preview frame.
276    * @param width The width of the image.
277    * @param height The height of the image.
278    * @return A PlanarYUVLuminanceSource instance.
279    */
280   public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
281     Rect rect = getFramingRectInPreview();
282     int previewFormat = configManager.getPreviewFormat();
283     String previewFormatString = configManager.getPreviewFormatString();
284     switch (previewFormat) {
285       // This is the standard Android format which all devices are REQUIRED to support.
286       // In theory, it's the only one we should ever care about.
287       case PixelFormat.YCbCr_420_SP:
288       // This format has never been seen in the wild, but is compatible as we only care
289       // about the Y channel, so allow it.
290       case PixelFormat.YCbCr_422_SP:
291         return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
292             rect.width(), rect.height());
293       default:
294         // The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
295         // Fortunately, it too has all the Y data up front, so we can read it.
296         if ("yuv420p".equals(previewFormatString)) {
297           return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
298             rect.width(), rect.height());
299         }
300     }
301     throw new IllegalArgumentException("Unsupported picture format: " +
302         previewFormat + '/' + previewFormatString);
303   }
304
305 }