Per Daniel -- don't check phone's preview size as we want to use screen size if possible
[zxing.git] / android / src / com / google / zxing / client / android / 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;
18
19 import com.google.zxing.ResultPoint;
20
21 import android.content.Context;
22 import android.graphics.PixelFormat;
23 import android.graphics.Point;
24 import android.graphics.Rect;
25 import android.hardware.Camera;
26 import android.os.Build;
27 import android.os.Handler;
28 import android.os.Message;
29 import android.util.Log;
30 import android.view.Display;
31 import android.view.SurfaceHolder;
32 import android.view.WindowManager;
33
34 import java.io.IOException;
35 import java.util.regex.Pattern;
36
37 /**
38  * This object wraps the Camera service object and expects to be the only one talking to it. The
39  * implementation encapsulates the steps needed to take preview-sized images, which are used for
40  * both preview and decoding.
41  *
42  * @author dswitkin@google.com (Daniel Switkin)
43  */
44 final class CameraManager {
45
46   private static final String TAG = "CameraManager";
47
48   private static final int MIN_FRAME_WIDTH = 240;
49   private static final int MIN_FRAME_HEIGHT = 240;
50   private static final int MAX_FRAME_WIDTH = 480;
51   private static final int MAX_FRAME_HEIGHT = 360;
52
53   private static final Pattern COMMA_PATTERN = Pattern.compile(",");
54
55   private static CameraManager cameraManager;
56
57   private Camera camera;
58   private final Context context;
59   private Point screenResolution;
60   private Point cameraResolution;
61   private Rect framingRect;
62   private Handler previewHandler;
63   private int previewMessage;
64   private Handler autoFocusHandler;
65   private int autoFocusMessage;
66   private boolean initialized;
67   private boolean previewing;
68   private int previewFormat;
69   private String previewFormatString;
70   private boolean useOneShotPreviewCallback;
71
72   /**
73    * Preview frames are delivered here, which we pass on to the registered handler. Make sure to
74    * clear the handler so it will only receive one message.
75    */
76   private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
77     public void onPreviewFrame(byte[] data, Camera camera) {
78       if (!useOneShotPreviewCallback) {
79         camera.setPreviewCallback(null);
80       }
81       if (previewHandler != null) {
82         Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,
83             cameraResolution.y, data);
84         message.sendToTarget();
85         previewHandler = null;
86       }
87     }
88   };
89
90   /**
91    * Autofocus callbacks arrive here, and are dispatched to the Handler which requested them.
92    */
93   private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
94     public void onAutoFocus(boolean success, Camera camera) {
95       if (autoFocusHandler != null) {
96         Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success);
97         // Simulate continuous autofocus by sending a focus request every 1.5 seconds.
98         autoFocusHandler.sendMessageDelayed(message, 1500L);
99         autoFocusHandler = null;
100       }
101     }
102   };
103
104   /**
105    * Initializes this static object with the Context of the calling Activity.
106    *
107    * @param context The Activity which wants to use the camera.
108    */
109   public static void init(Context context) {
110     if (cameraManager == null) {
111       cameraManager = new CameraManager(context);
112     }
113   }
114
115   /**
116    * Gets the CameraManager singleton instance.
117    *
118    * @return A reference to the CameraManager singleton.
119    */
120   public static CameraManager get() {
121     return cameraManager;
122   }
123
124   private CameraManager(Context context) {
125     this.context = context;
126     camera = null;
127     initialized = false;
128     previewing = false;
129
130     // Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older
131     // Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use
132     // the more efficient one shot callback, as the older one can swamp the system and cause it
133     // to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.
134     useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;
135   }
136
137   /**
138    * Opens the camera driver and initializes the hardware parameters.
139    *
140    * @param holder The surface object which the camera will draw preview frames into.
141    * @throws IOException Indicates the camera driver failed to open.
142    */
143   public void openDriver(SurfaceHolder holder) throws IOException {
144     if (camera == null) {
145       camera = Camera.open();
146       if (camera == null) {
147         throw new IOException();
148       }
149       camera.setPreviewDisplay(holder);
150
151       if (!initialized) {
152         initialized = true;
153         getScreenResolution();
154       }
155
156       setCameraParameters();
157       FlashlightManager.enableFlashlight();
158     }
159   }
160
161   /**
162    * Closes the camera driver if still in use.
163    */
164   public void closeDriver() {
165     if (camera != null) {
166       FlashlightManager.disableFlashlight();
167       camera.release();
168       camera = null;
169     }
170   }
171
172   /**
173    * Asks the camera hardware to begin drawing preview frames to the screen.
174    */
175   public void startPreview() {
176     if (camera != null && !previewing) {
177       camera.startPreview();
178       previewing = true;
179     }
180   }
181
182   /**
183    * Tells the camera to stop drawing preview frames.
184    */
185   public void stopPreview() {
186     if (camera != null && previewing) {
187       if (!useOneShotPreviewCallback) {
188         camera.setPreviewCallback(null);
189       }
190       camera.stopPreview();
191       previewHandler = null;
192       autoFocusHandler = null;
193       previewing = false;
194     }
195   }
196
197   /**
198    * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
199    * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
200    * respectively.
201    *
202    * @param handler The handler to send the message to.
203    * @param message The what field of the message to be sent.
204    */
205   public void requestPreviewFrame(Handler handler, int message) {
206     if (camera != null && previewing) {
207       previewHandler = handler;
208       previewMessage = message;
209       if (useOneShotPreviewCallback) {
210         camera.setOneShotPreviewCallback(previewCallback);
211       } else {
212         camera.setPreviewCallback(previewCallback);
213       }
214     }
215   }
216
217   /**
218    * Asks the camera hardware to perform an autofocus.
219    *
220    * @param handler The Handler to notify when the autofocus completes.
221    * @param message The message to deliver.
222    */
223   public void requestAutoFocus(Handler handler, int message) {
224     if (camera != null && previewing) {
225       autoFocusHandler = handler;
226       autoFocusMessage = message;
227       camera.autoFocus(autoFocusCallback);
228     }
229   }
230
231   /**
232    * Calculates the framing rect which the UI should draw to show the user where to place the
233    * barcode. This target helps with alignment as well as forces the user to hold the device
234    * far enough away to ensure the image will be in focus.
235    *
236    * @return The rectangle to draw on screen in window coordinates.
237    */
238   public Rect getFramingRect() {
239     if (framingRect == null) {
240       if (camera == null) {
241         return null;
242       }
243       int width = cameraResolution.x * 3 / 4;
244       if (width < MIN_FRAME_WIDTH) {
245         width = MIN_FRAME_WIDTH;
246       } else if (width > MAX_FRAME_WIDTH) {
247         width = MAX_FRAME_WIDTH;
248       }
249       int height = cameraResolution.y * 3 / 4;
250       if (height < MIN_FRAME_HEIGHT) {
251         height = MIN_FRAME_HEIGHT;
252       } else if (height > MAX_FRAME_HEIGHT) {
253         height = MAX_FRAME_HEIGHT;
254       }
255       int leftOffset = (cameraResolution.x - width) / 2;
256       int topOffset = (cameraResolution.y - height) / 2;
257       framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
258       Log.v(TAG, "Calculated framing rect: " + framingRect);
259     }
260     return framingRect;
261   }
262
263   /**
264    * Converts the result points from still resolution coordinates to screen coordinates.
265    *
266    * @param points The points returned by the Reader subclass through Result.getResultPoints().
267    * @return An array of Points scaled to the size of the framing rect and offset appropriately
268    *         so they can be drawn in screen coordinates.
269    */
270   public Point[] convertResultPoints(ResultPoint[] points) {
271     Rect frame = getFramingRect();
272     int count = points.length;
273     Point[] output = new Point[count];
274     for (int x = 0; x < count; x++) {
275       output[x] = new Point();
276       output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
277       output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
278     }
279     return output;
280   }
281
282   /**
283    * A factory method to build the appropriate LuminanceSource object based on the format
284    * of the preview buffers, as described by Camera.Parameters.
285    *
286    * @param data A preview frame.
287    * @param width The width of the image.
288    * @param height The height of the image.
289    * @return A PlanarYUVLuminanceSource instance.
290    */
291   public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
292     Rect rect = getFramingRect();
293     switch (previewFormat) {
294       // This is the standard Android format which all devices are REQUIRED to support.
295       // In theory, it's the only one we should ever care about.
296       case PixelFormat.YCbCr_420_SP:
297       // This format has never been seen in the wild, but is compatible as we only care
298       // about the Y channel, so allow it.
299       case PixelFormat.YCbCr_422_SP:
300         return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
301             rect.width(), rect.height());
302       default:
303         // The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
304         // Fortunately, it too has all the Y data up front, so we can read it.
305         if ("yuv420p".equals(previewFormatString)) {
306           return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
307             rect.width(), rect.height());
308         }
309     }
310     throw new IllegalArgumentException("Unsupported picture format: " +
311         previewFormat + '/' + previewFormatString);
312   }
313
314   /**
315    * Sets the camera up to take preview images which are used for both preview and decoding.
316    * We detect the preview format here so that buildLuminanceSource() can build an appropriate
317    * LuminanceSource subclass. In the future we may want to force YUV420SP as it's the smallest,
318    * and the planar Y can be used for barcode scanning without a copy in some cases.
319    */
320   private void setCameraParameters() {
321     Camera.Parameters parameters = camera.getParameters();
322     previewFormat = parameters.getPreviewFormat();
323     previewFormatString = parameters.get("preview-format");
324     Log.v(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
325
326     cameraResolution = getCameraResolution(parameters);
327     Log.v(TAG, "Setting preview size: " + cameraResolution.x + ", " + cameraResolution.y);
328     parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
329
330     // FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
331     parameters.set("flash-value", 2);
332
333     // This is the standard setting to turn the flash off that all devices should honor.
334     parameters.set("flash-mode", "off");
335
336     // Set zoom to 2x if available. This helps encourage the user to pull back.
337     // Some devices like the Behold have a zoom parameter
338     parameters.set("zoom", "2.0");
339     // Most devices, like the Hero, appear to expose this zoom parameter.
340     // (I think) This means 2.0x
341     parameters.set("taking-picture-zoom", "20");
342
343     camera.setParameters(parameters);
344   }
345
346   private Point getScreenResolution() {
347     if (screenResolution == null) {
348       WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
349       Display display = manager.getDefaultDisplay();
350       screenResolution = new Point(display.getWidth(), display.getHeight());
351     }
352     return screenResolution;
353   }
354
355   private Point getCameraResolution(Camera.Parameters parameters) {
356
357     String previewSizeValueString = parameters.get("preview-size-values");
358     // saw this on Xperia
359     if (previewSizeValueString == null) {
360       previewSizeValueString = parameters.get("preview-size-value");
361     }
362
363     Point cameraResolution = null;
364     
365     if (previewSizeValueString != null) {
366       Log.v(TAG, "preview-size parameter: " + previewSizeValueString);
367       cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
368     }
369
370     if (cameraResolution == null) {
371       // Ensure that the camera resolution is a multiple of 8, as the screen may not be.
372       cameraResolution = new Point(
373           (screenResolution.x >> 3) << 3,
374           (screenResolution.y >> 3) << 3);
375     }
376
377     return cameraResolution;
378   }
379
380   private static Point findBestPreviewSizeValue(String previewSizeValueString, Point screenResolution) {
381     int bestX = 0;
382     int bestY = 0;
383     int diff = Integer.MAX_VALUE;
384     for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
385
386       previewSize = previewSize.trim();
387       int dimPosition = previewSize.indexOf('x');
388       if (dimPosition < 0) {
389         Log.w(TAG, "Bad preview-size");
390         continue;
391       }
392
393       int newX;
394       int newY;
395       try {
396         newX = Integer.parseInt(previewSize.substring(0, dimPosition));
397         newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
398       } catch (NumberFormatException nfe) {
399         Log.w(TAG, "Bad preview-size");
400         continue;
401       }
402
403       int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
404       if (newDiff == 0) {
405         bestX = newX;
406         bestY = newY;
407         break;
408       } else if (newDiff < diff) {
409         bestX = newX;
410         bestY = newY;
411         diff = newDiff;
412       }
413
414     }
415
416     if (bestX > 0 && bestY > 0) {
417       return new Point(bestX, bestY);
418     }
419     return null;
420   }
421
422 }