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();
157 FlashlightManager.enableFlashlight();
162 * Closes the camera driver if still in use.
164 public void closeDriver() {
165 if (camera != null) {
166 FlashlightManager.disableFlashlight();
173 * Asks the camera hardware to begin drawing preview frames to the screen.
175 public void startPreview() {
176 if (camera != null && !previewing) {
177 camera.startPreview();
183 * Tells the camera to stop drawing preview frames.
185 public void stopPreview() {
186 if (camera != null && previewing) {
187 if (!useOneShotPreviewCallback) {
188 camera.setPreviewCallback(null);
190 camera.stopPreview();
191 previewHandler = null;
192 autoFocusHandler = null;
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,
202 * @param handler The handler to send the message to.
203 * @param message The what field of the message to be sent.
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);
212 camera.setPreviewCallback(previewCallback);
218 * Asks the camera hardware to perform an autofocus.
220 * @param handler The Handler to notify when the autofocus completes.
221 * @param message The message to deliver.
223 public void requestAutoFocus(Handler handler, int message) {
224 if (camera != null && previewing) {
225 autoFocusHandler = handler;
226 autoFocusMessage = message;
227 camera.autoFocus(autoFocusCallback);
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.
236 * @return The rectangle to draw on screen in window coordinates.
238 public Rect getFramingRect() {
239 if (framingRect == null) {
240 if (camera == null) {
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;
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;
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);
264 * Converts the result points from still resolution coordinates to screen coordinates.
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.
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);
283 * A factory method to build the appropriate LuminanceSource object based on the format
284 * of the preview buffers, as described by Camera.Parameters.
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.
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());
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());
310 throw new IllegalArgumentException("Unsupported picture format: " +
311 previewFormat + '/' + previewFormatString);
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.
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);
326 cameraResolution = getCameraResolution(parameters);
327 Log.v(TAG, "Setting preview size: " + cameraResolution.x + ", " + cameraResolution.y);
328 parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
330 // FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
331 parameters.set("flash-value", 2);
333 // This is the standard setting to turn the flash off that all devices should honor.
334 parameters.set("flash-mode", "off");
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");
343 camera.setParameters(parameters);
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());
352 return screenResolution;
355 private Point getCameraResolution(Camera.Parameters parameters) {
357 String previewSizeValueString = parameters.get("preview-size-values");
358 // saw this on Xperia
359 if (previewSizeValueString == null) {
360 previewSizeValueString = parameters.get("preview-size-value");
363 Point cameraResolution = null;
365 if (previewSizeValueString != null) {
366 Log.v(TAG, "preview-size parameter: " + previewSizeValueString);
367 cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
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);
377 return cameraResolution;
380 private static Point findBestPreviewSizeValue(String previewSizeValueString, Point screenResolution) {
383 int diff = Integer.MAX_VALUE;
384 for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
386 previewSize = previewSize.trim();
387 int dimPosition = previewSize.indexOf('x');
388 if (dimPosition < 0) {
389 Log.w(TAG, "Bad preview-size");
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");
403 int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
408 } else if (newDiff < diff) {
416 if (bestX > 0 && bestY > 0) {
417 return new Point(bestX, bestY);