Fix r1221 logic
[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     }
158   }
159
160   /**
161    * Closes the camera driver if still in use.
162    */
163   public void closeDriver() {
164     if (camera != null) {
165       camera.release();
166       camera = null;
167     }
168   }
169
170   /**
171    * Asks the camera hardware to begin drawing preview frames to the screen.
172    */
173   public void startPreview() {
174     if (camera != null && !previewing) {
175       camera.startPreview();
176       previewing = true;
177     }
178   }
179
180   /**
181    * Tells the camera to stop drawing preview frames.
182    */
183   public void stopPreview() {
184     if (camera != null && previewing) {
185       if (!useOneShotPreviewCallback) {
186         camera.setPreviewCallback(null);
187       }
188       camera.stopPreview();
189       previewHandler = null;
190       autoFocusHandler = null;
191       previewing = false;
192     }
193   }
194
195   /**
196    * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
197    * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
198    * respectively.
199    *
200    * @param handler The handler to send the message to.
201    * @param message The what field of the message to be sent.
202    */
203   public void requestPreviewFrame(Handler handler, int message) {
204     if (camera != null && previewing) {
205       previewHandler = handler;
206       previewMessage = message;
207       if (useOneShotPreviewCallback) {
208         camera.setOneShotPreviewCallback(previewCallback);
209       } else {
210         camera.setPreviewCallback(previewCallback);
211       }
212     }
213   }
214
215   /**
216    * Asks the camera hardware to perform an autofocus.
217    *
218    * @param handler The Handler to notify when the autofocus completes.
219    * @param message The message to deliver.
220    */
221   public void requestAutoFocus(Handler handler, int message) {
222     if (camera != null && previewing) {
223       autoFocusHandler = handler;
224       autoFocusMessage = message;
225       camera.autoFocus(autoFocusCallback);
226     }
227   }
228
229   /**
230    * Calculates the framing rect which the UI should draw to show the user where to place the
231    * barcode. This target helps with alignment as well as forces the user to hold the device
232    * far enough away to ensure the image will be in focus.
233    *
234    * @return The rectangle to draw on screen in window coordinates.
235    */
236   public Rect getFramingRect() {
237     if (framingRect == null) {
238       if (camera == null) {
239         return null;
240       }
241       int width = cameraResolution.x * 3 / 4;
242       if (width < MIN_FRAME_WIDTH) {
243         width = MIN_FRAME_WIDTH;
244       } else if (width > MAX_FRAME_WIDTH) {
245         width = MAX_FRAME_WIDTH;
246       }
247       int height = cameraResolution.y * 3 / 4;
248       if (height < MIN_FRAME_HEIGHT) {
249         height = MIN_FRAME_HEIGHT;
250       } else if (height > MAX_FRAME_HEIGHT) {
251         height = MAX_FRAME_HEIGHT;
252       }
253       int leftOffset = (cameraResolution.x - width) / 2;
254       int topOffset = (cameraResolution.y - height) / 2;
255       framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
256       Log.v(TAG, "Calculated framing rect: " + framingRect);
257     }
258     return framingRect;
259   }
260
261   /**
262    * Converts the result points from still resolution coordinates to screen coordinates.
263    *
264    * @param points The points returned by the Reader subclass through Result.getResultPoints().
265    * @return An array of Points scaled to the size of the framing rect and offset appropriately
266    *         so they can be drawn in screen coordinates.
267    */
268   public Point[] convertResultPoints(ResultPoint[] points) {
269     Rect frame = getFramingRect();
270     int count = points.length;
271     Point[] output = new Point[count];
272     for (int x = 0; x < count; x++) {
273       output[x] = new Point();
274       output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
275       output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
276     }
277     return output;
278   }
279
280   /**
281    * A factory method to build the appropriate LuminanceSource object based on the format
282    * of the preview buffers, as described by Camera.Parameters.
283    *
284    * @param data A preview frame.
285    * @param width The width of the image.
286    * @param height The height of the image.
287    * @return A PlanarYUVLuminanceSource instance.
288    */
289   public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
290     Rect rect = getFramingRect();
291     switch (previewFormat) {
292       // This is the standard Android format which all devices are REQUIRED to support.
293       // In theory, it's the only one we should ever care about.
294       case PixelFormat.YCbCr_420_SP:
295       // This format has never been seen in the wild, but is compatible as we only care
296       // about the Y channel, so allow it.
297       case PixelFormat.YCbCr_422_SP:
298         return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
299             rect.width(), rect.height());
300       default:
301         // The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
302         // Fortunately, it too has all the Y data up front, so we can read it.
303         if ("yuv420p".equals(previewFormatString)) {
304           return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
305             rect.width(), rect.height());
306         }
307     }
308     throw new IllegalArgumentException("Unsupported picture format: " +
309         previewFormat + '/' + previewFormatString);
310   }
311
312   /**
313    * Sets the camera up to take preview images which are used for both preview and decoding.
314    * We detect the preview format here so that buildLuminanceSource() can build an appropriate
315    * LuminanceSource subclass. In the future we may want to force YUV420SP as it's the smallest,
316    * and the planar Y can be used for barcode scanning without a copy in some cases.
317    */
318   private void setCameraParameters() {
319     Camera.Parameters parameters = camera.getParameters();
320     previewFormat = parameters.getPreviewFormat();
321     previewFormatString = parameters.get("preview-format");
322     Log.v(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
323
324     cameraResolution = getCameraResolution(parameters);
325     Log.v(TAG, "Setting preview size: " + cameraResolution.x + ", " + cameraResolution.y);
326     parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
327
328     // FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
329     parameters.set("flash-value", 2);
330
331     // This is the standard setting to turn the flash off that all devices should honor.
332     parameters.set("flash-mode", "off");
333
334     // Set zoom to 2x if available. This helps encourage the user to pull back.
335     // Some devices like the Behold have a zoom parameter
336     parameters.set("zoom", "2.0");
337     // Most devices, like the Hero, appear to expose this zoom parameter.
338     // (I think) This means 2.0x
339     parameters.set("taking-picture-zoom", "20");
340
341     camera.setParameters(parameters);
342   }
343
344   private Point getScreenResolution() {
345     if (screenResolution == null) {
346       WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
347       Display display = manager.getDefaultDisplay();
348       screenResolution = new Point(display.getWidth(), display.getHeight());
349     }
350     return screenResolution;
351   }
352
353   private Point getCameraResolution(Camera.Parameters parameters) {
354
355     Point cameraResolution = null;
356
357     Camera.Size cameraPreviewSize = parameters.getPreviewSize();
358     if (cameraPreviewSize != null) {
359       Log.v(TAG, "Default preview size: " + cameraPreviewSize.width + ", " + cameraPreviewSize.height);
360       cameraResolution = new Point(cameraPreviewSize.width, cameraPreviewSize.height);
361     }
362
363     if (cameraResolution == null) {
364       String previewSizeValueString = parameters.get("preview-size-values");
365       // saw this on Xperia
366       if (previewSizeValueString == null) {
367         previewSizeValueString = parameters.get("preview-size-value");
368       }
369       if (previewSizeValueString != null) {
370         Log.v(TAG, "preview-size parameter: " + previewSizeValueString);
371         cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
372       }
373     }
374
375     if (cameraResolution == null) {
376       // Ensure that the camera resolution is a multiple of 8, as the screen may not be.
377       cameraResolution = new Point(
378           (screenResolution.x >> 3) << 3,
379           (screenResolution.y >> 3) << 3);
380     }
381
382     return cameraResolution;
383   }
384
385   private static Point findBestPreviewSizeValue(String previewSizeValueString, Point screenResolution) {
386     int bestX = 0;
387     int bestY = 0;
388     int diff = Integer.MAX_VALUE;
389     for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
390
391       previewSize = previewSize.trim();
392       int dimPosition = previewSize.indexOf('x');
393       if (dimPosition < 0) {
394         Log.w(TAG, "Bad preview-size");
395         continue;
396       }
397
398       int newX;
399       int newY;
400       try {
401         newX = Integer.parseInt(previewSize.substring(0, dimPosition));
402         newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
403       } catch (NumberFormatException nfe) {
404         Log.w(TAG, "Bad preview-size");
405         continue;
406       }
407
408       int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
409       if (newDiff == 0) {
410         bestX = newX;
411         bestY = newY;
412         break;
413       } else if (newDiff < diff) {
414         bestX = newX;
415         bestY = newY;
416         diff = newDiff;
417       }
418
419     }
420
421     if (bestX > 0 && bestY > 0) {
422       return new Point(bestX, bestY);
423     }
424     return null;
425   }
426
427 }