2 * Copyright (C) 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.client.android;
19 import com.google.zxing.ResultPoint;
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;
34 import java.io.IOException;
35 import java.util.regex.Pattern;
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.
42 * @author dswitkin@google.com (Daniel Switkin)
44 final class CameraManager {
46 private static final String TAG = "CameraManager";
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;
53 private static final Pattern COMMA_PATTERN = Pattern.compile(",");
55 private static CameraManager cameraManager;
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;
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.
76 private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
77 public void onPreviewFrame(byte[] data, Camera camera) {
78 if (!useOneShotPreviewCallback) {
79 camera.setPreviewCallback(null);
81 if (previewHandler != null) {
82 Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,
83 cameraResolution.y, data);
84 message.sendToTarget();
85 previewHandler = null;
91 * Autofocus callbacks arrive here, and are dispatched to the Handler which requested them.
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;
105 * Initializes this static object with the Context of the calling Activity.
107 * @param context The Activity which wants to use the camera.
109 public static void init(Context context) {
110 if (cameraManager == null) {
111 cameraManager = new CameraManager(context);
116 * Gets the CameraManager singleton instance.
118 * @return A reference to the CameraManager singleton.
120 public static CameraManager get() {
121 return cameraManager;
124 private CameraManager(Context context) {
125 this.context = context;
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;
138 * Opens the camera driver and initializes the hardware parameters.
140 * @param holder The surface object which the camera will draw preview frames into.
141 * @throws IOException Indicates the camera driver failed to open.
143 public void openDriver(SurfaceHolder holder) throws IOException {
144 if (camera == null) {
145 camera = Camera.open();
146 if (camera == null) {
147 throw new IOException();
149 camera.setPreviewDisplay(holder);
153 getScreenResolution();
156 setCameraParameters();
161 * Closes the camera driver if still in use.
163 public void closeDriver() {
164 if (camera != null) {
171 * Asks the camera hardware to begin drawing preview frames to the screen.
173 public void startPreview() {
174 if (camera != null && !previewing) {
175 camera.startPreview();
181 * Tells the camera to stop drawing preview frames.
183 public void stopPreview() {
184 if (camera != null && previewing) {
185 if (!useOneShotPreviewCallback) {
186 camera.setPreviewCallback(null);
188 camera.stopPreview();
189 previewHandler = null;
190 autoFocusHandler = null;
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,
200 * @param handler The handler to send the message to.
201 * @param message The what field of the message to be sent.
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);
210 camera.setPreviewCallback(previewCallback);
216 * Asks the camera hardware to perform an autofocus.
218 * @param handler The Handler to notify when the autofocus completes.
219 * @param message The message to deliver.
221 public void requestAutoFocus(Handler handler, int message) {
222 if (camera != null && previewing) {
223 autoFocusHandler = handler;
224 autoFocusMessage = message;
225 camera.autoFocus(autoFocusCallback);
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.
234 * @return The rectangle to draw on screen in window coordinates.
236 public Rect getFramingRect() {
237 if (framingRect == null) {
238 if (camera == null) {
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;
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;
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);
262 * Converts the result points from still resolution coordinates to screen coordinates.
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.
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);
281 * A factory method to build the appropriate LuminanceSource object based on the format
282 * of the preview buffers, as described by Camera.Parameters.
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.
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());
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());
308 throw new IllegalArgumentException("Unsupported picture format: " +
309 previewFormat + '/' + previewFormatString);
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.
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);
324 cameraResolution = getCameraResolution(parameters);
325 Log.v(TAG, "Setting preview size: " + cameraResolution.x + ", " + cameraResolution.y);
326 parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
328 // FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
329 parameters.set("flash-value", 2);
331 // This is the standard setting to turn the flash off that all devices should honor.
332 parameters.set("flash-mode", "off");
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");
341 camera.setParameters(parameters);
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());
350 return screenResolution;
353 private Point getCameraResolution(Camera.Parameters parameters) {
355 Point cameraResolution = null;
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);
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");
369 if (previewSizeValueString != null) {
370 Log.v(TAG, "preview-size parameter: " + previewSizeValueString);
371 cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
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);
382 return cameraResolution;
385 private static Point findBestPreviewSizeValue(String previewSizeValueString, Point screenResolution) {
388 int diff = Integer.MAX_VALUE;
389 for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
391 previewSize = previewSize.trim();
392 int dimPosition = previewSize.indexOf('x');
393 if (dimPosition < 0) {
394 Log.w(TAG, "Bad preview-size");
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");
408 int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
413 } else if (newDiff < diff) {
421 if (bestX > 0 && bestY > 0) {
422 return new Point(bestX, bestY);