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.camera;
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;
33 import java.io.IOException;
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.
40 * @author dswitkin@google.com (Daniel Switkin)
42 public final class CameraManager {
44 private static final String TAG = CameraManager.class.getSimpleName();
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;
51 private static CameraManager cameraManager;
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;
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.
65 private final PreviewCallback previewCallback;
66 /** Autofocus callbacks arrive here, and are dispatched to the Handler which requested them. */
67 private final AutoFocusCallback autoFocusCallback;
70 * Initializes this static object with the Context of the calling Activity.
72 * @param context The Activity which wants to use the camera.
74 public static void init(Context context) {
75 if (cameraManager == null) {
76 cameraManager = new CameraManager(context);
81 * Gets the CameraManager singleton instance.
83 * @return A reference to the CameraManager singleton.
85 public static CameraManager get() {
89 private CameraManager(Context context) {
91 this.context = context;
92 this.configManager = new CameraConfigurationManager(context);
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;
100 previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);
101 autoFocusCallback = new AutoFocusCallback(configManager);
105 * Opens the camera driver and initializes the hardware parameters.
107 * @param holder The surface object which the camera will draw preview frames into.
108 * @throws IOException Indicates the camera driver failed to open.
110 public void openDriver(SurfaceHolder holder) throws IOException {
111 if (camera == null) {
112 camera = Camera.open();
113 if (camera == null) {
114 throw new IOException();
116 camera.setPreviewDisplay(holder);
120 configManager.initFromCameraParameters(camera);
122 configManager.setDesiredCameraParameters(camera);
124 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
125 if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {
126 FlashlightManager.enableFlashlight();
132 * Closes the camera driver if still in use.
134 public void closeDriver() {
135 if (camera != null) {
136 FlashlightManager.disableFlashlight();
143 * Asks the camera hardware to begin drawing preview frames to the screen.
145 public void startPreview() {
146 if (camera != null && !previewing) {
147 camera.startPreview();
153 * Tells the camera to stop drawing preview frames.
155 public void stopPreview() {
156 if (camera != null && previewing) {
157 if (!useOneShotPreviewCallback) {
158 camera.setPreviewCallback(null);
160 camera.stopPreview();
161 previewCallback.setHandler(null, 0);
162 autoFocusCallback.setHandler(null, 0);
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,
172 * @param handler The handler to send the message to.
173 * @param message The what field of the message to be sent.
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);
181 camera.setPreviewCallback(previewCallback);
187 * Asks the camera hardware to perform an autofocus.
189 * @param handler The Handler to notify when the autofocus completes.
190 * @param message The message to deliver.
192 public void requestAutoFocus(Handler handler, int message) {
193 if (camera != null && previewing) {
194 autoFocusCallback.setHandler(handler, message);
195 Log.v(TAG, "Requesting auto-focus callback");
196 camera.autoFocus(autoFocusCallback);
201 * Calculates the framing rect which the UI should draw to show the user where to place the
202 * barcode. This target helps with alignment as well as forces the user to hold the device
203 * far enough away to ensure the image will be in focus.
205 * @return The rectangle to draw on screen in window coordinates.
207 public Rect getFramingRect() {
208 Point screenResolution = configManager.getScreenResolution();
209 if (framingRect == null) {
210 if (camera == null) {
213 int width = screenResolution.x * 3 / 4;
214 if (width < MIN_FRAME_WIDTH) {
215 width = MIN_FRAME_WIDTH;
216 } else if (width > MAX_FRAME_WIDTH) {
217 width = MAX_FRAME_WIDTH;
219 int height = screenResolution.y * 3 / 4;
220 if (height < MIN_FRAME_HEIGHT) {
221 height = MIN_FRAME_HEIGHT;
222 } else if (height > MAX_FRAME_HEIGHT) {
223 height = MAX_FRAME_HEIGHT;
225 int leftOffset = (screenResolution.x - width) / 2;
226 int topOffset = (screenResolution.y - height) / 2;
227 framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
228 Log.v(TAG, "Calculated framing rect: " + framingRect);
234 * Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
237 public Rect getFramingRectInPreview() {
238 if (framingRectInPreview == null) {
239 Rect rect = new Rect(getFramingRect());
240 Point cameraResolution = configManager.getCameraResolution();
241 Point screenResolution = configManager.getScreenResolution();
242 rect.left = rect.left * cameraResolution.x / screenResolution.x;
243 rect.right = rect.right * cameraResolution.x / screenResolution.x;
244 rect.top = rect.top * cameraResolution.y / screenResolution.y;
245 rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
246 framingRectInPreview = rect;
248 return framingRectInPreview;
252 * Converts the result points from still resolution coordinates to screen coordinates.
254 * @param points The points returned by the Reader subclass through Result.getResultPoints().
255 * @return An array of Points scaled to the size of the framing rect and offset appropriately
256 * so they can be drawn in screen coordinates.
259 public Point[] convertResultPoints(ResultPoint[] points) {
260 Rect frame = getFramingRectInPreview();
261 int count = points.length;
262 Point[] output = new Point[count];
263 for (int x = 0; x < count; x++) {
264 output[x] = new Point();
265 output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
266 output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
273 * A factory method to build the appropriate LuminanceSource object based on the format
274 * of the preview buffers, as described by Camera.Parameters.
276 * @param data A preview frame.
277 * @param width The width of the image.
278 * @param height The height of the image.
279 * @return A PlanarYUVLuminanceSource instance.
281 public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
282 Rect rect = getFramingRectInPreview();
283 int previewFormat = configManager.getPreviewFormat();
284 String previewFormatString = configManager.getPreviewFormatString();
285 switch (previewFormat) {
286 // This is the standard Android format which all devices are REQUIRED to support.
287 // In theory, it's the only one we should ever care about.
288 case PixelFormat.YCbCr_420_SP:
289 // This format has never been seen in the wild, but is compatible as we only care
290 // about the Y channel, so allow it.
291 case PixelFormat.YCbCr_422_SP:
292 return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
293 rect.width(), rect.height());
295 // The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
296 // Fortunately, it too has all the Y data up front, so we can read it.
297 if ("yuv420p".equals(previewFormatString)) {
298 return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
299 rect.width(), rect.height());
302 throw new IllegalArgumentException("Unsupported picture format: " +
303 previewFormat + '/' + previewFormatString);