a02550a5b89dfc959e816fea26cba90493ca5fbd
[zxing.git] / android / src / com / google / zxing / client / android / camera / 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.camera;
18
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;
32
33 import java.io.IOException;
34
35 /**
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.
39  *
40  * @author dswitkin@google.com (Daniel Switkin)
41  */
42 public final class CameraManager {
43
44   private static final String TAG = CameraManager.class.getSimpleName();
45
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;
50
51   private static CameraManager cameraManager;
52
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;
61   /**
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.
64    */
65   private final PreviewCallback previewCallback;
66   /** Autofocus callbacks arrive here, and are dispatched to the Handler which requested them. */
67   private final AutoFocusCallback autoFocusCallback;
68
69   /**
70    * Initializes this static object with the Context of the calling Activity.
71    *
72    * @param context The Activity which wants to use the camera.
73    */
74   public static void init(Context context) {
75     if (cameraManager == null) {
76       cameraManager = new CameraManager(context);
77     }
78   }
79
80   /**
81    * Gets the CameraManager singleton instance.
82    *
83    * @return A reference to the CameraManager singleton.
84    */
85   public static CameraManager get() {
86     return cameraManager;
87   }
88
89   private CameraManager(Context context) {
90
91     this.context = context;
92     this.configManager = new CameraConfigurationManager(context);
93
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;
99
100     previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);
101     autoFocusCallback = new AutoFocusCallback(configManager);
102   }
103
104   /**
105    * Opens the camera driver and initializes the hardware parameters.
106    *
107    * @param holder The surface object which the camera will draw preview frames into.
108    * @throws IOException Indicates the camera driver failed to open.
109    */
110   public void openDriver(SurfaceHolder holder) throws IOException {
111     if (camera == null) {
112       camera = Camera.open();
113       if (camera == null) {
114         throw new IOException();
115       }
116       camera.setPreviewDisplay(holder);
117
118       if (!initialized) {
119         initialized = true;
120         configManager.initFromCameraParameters(camera);
121       }
122       configManager.setDesiredCameraParameters(camera);
123
124       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
125       if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {
126         FlashlightManager.enableFlashlight();
127       }
128     }
129   }
130
131   /**
132    * Closes the camera driver if still in use.
133    */
134   public void closeDriver() {
135     if (camera != null) {
136       FlashlightManager.disableFlashlight();
137       camera.release();
138       camera = null;
139     }
140   }
141
142   /**
143    * Asks the camera hardware to begin drawing preview frames to the screen.
144    */
145   public void startPreview() {
146     if (camera != null && !previewing) {
147       camera.startPreview();
148       previewing = true;
149     }
150   }
151
152   /**
153    * Tells the camera to stop drawing preview frames.
154    */
155   public void stopPreview() {
156     if (camera != null && previewing) {
157       if (!useOneShotPreviewCallback) {
158         camera.setPreviewCallback(null);
159       }
160       camera.stopPreview();
161       previewCallback.setHandler(null, 0);
162       autoFocusCallback.setHandler(null, 0);
163       previewing = false;
164     }
165   }
166
167   /**
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,
170    * respectively.
171    *
172    * @param handler The handler to send the message to.
173    * @param message The what field of the message to be sent.
174    */
175   public void requestPreviewFrame(Handler handler, int message) {
176     if (camera != null && previewing) {
177       previewCallback.setHandler(handler, message);
178       if (useOneShotPreviewCallback) {
179         Log.v(TAG, "Requesting one-shot preview callback");
180         camera.setOneShotPreviewCallback(previewCallback);
181       } else {
182         Log.v(TAG, "Requesting preview callback");
183         camera.setPreviewCallback(previewCallback);
184       }
185     }
186   }
187
188   /**
189    * Asks the camera hardware to perform an autofocus.
190    *
191    * @param handler The Handler to notify when the autofocus completes.
192    * @param message The message to deliver.
193    */
194   public void requestAutoFocus(Handler handler, int message) {
195     if (camera != null && previewing) {
196       autoFocusCallback.setHandler(handler, message);
197       Log.v(TAG, "Requesting auto-focus callback");
198       camera.autoFocus(autoFocusCallback);
199     }
200   }
201
202   /**
203    * Calculates the framing rect which the UI should draw to show the user where to place the
204    * barcode. This target helps with alignment as well as forces the user to hold the device
205    * far enough away to ensure the image will be in focus.
206    *
207    * @return The rectangle to draw on screen in window coordinates.
208    */
209   public Rect getFramingRect() {
210     Point screenResolution = configManager.getScreenResolution();
211     if (framingRect == null) {
212       if (camera == null) {
213         return null;
214       }
215       int width = screenResolution.x * 3 / 4;
216       if (width < MIN_FRAME_WIDTH) {
217         width = MIN_FRAME_WIDTH;
218       } else if (width > MAX_FRAME_WIDTH) {
219         width = MAX_FRAME_WIDTH;
220       }
221       int height = screenResolution.y * 3 / 4;
222       if (height < MIN_FRAME_HEIGHT) {
223         height = MIN_FRAME_HEIGHT;
224       } else if (height > MAX_FRAME_HEIGHT) {
225         height = MAX_FRAME_HEIGHT;
226       }
227       int leftOffset = (screenResolution.x - width) / 2;
228       int topOffset = (screenResolution.y - height) / 2;
229       framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
230       Log.v(TAG, "Calculated framing rect: " + framingRect);
231     }
232     return framingRect;
233   }
234
235   /**
236    * Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
237    * not UI / screen.
238    */
239   public Rect getFramingRectInPreview() {
240     if (framingRectInPreview == null) {
241       Rect rect = new Rect(getFramingRect());
242       Point cameraResolution = configManager.getCameraResolution();
243       Point screenResolution = configManager.getScreenResolution();
244       rect.left = rect.left * cameraResolution.x / screenResolution.x;
245       rect.right = rect.right * cameraResolution.x / screenResolution.x;
246       rect.top = rect.top * cameraResolution.y / screenResolution.y;
247       rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
248       framingRectInPreview = rect;
249     }
250     return framingRectInPreview;
251   }
252
253   /**
254    * Converts the result points from still resolution coordinates to screen coordinates.
255    *
256    * @param points The points returned by the Reader subclass through Result.getResultPoints().
257    * @return An array of Points scaled to the size of the framing rect and offset appropriately
258    *         so they can be drawn in screen coordinates.
259    */
260   /*
261   public Point[] convertResultPoints(ResultPoint[] points) {
262     Rect frame = getFramingRectInPreview();
263     int count = points.length;
264     Point[] output = new Point[count];
265     for (int x = 0; x < count; x++) {
266       output[x] = new Point();
267       output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
268       output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
269     }
270     return output;
271   }
272    */
273
274   /**
275    * A factory method to build the appropriate LuminanceSource object based on the format
276    * of the preview buffers, as described by Camera.Parameters.
277    *
278    * @param data A preview frame.
279    * @param width The width of the image.
280    * @param height The height of the image.
281    * @return A PlanarYUVLuminanceSource instance.
282    */
283   public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
284     Rect rect = getFramingRectInPreview();
285     int previewFormat = configManager.getPreviewFormat();
286     String previewFormatString = configManager.getPreviewFormatString();
287     switch (previewFormat) {
288       // This is the standard Android format which all devices are REQUIRED to support.
289       // In theory, it's the only one we should ever care about.
290       case PixelFormat.YCbCr_420_SP:
291       // This format has never been seen in the wild, but is compatible as we only care
292       // about the Y channel, so allow it.
293       case PixelFormat.YCbCr_422_SP:
294         return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
295             rect.width(), rect.height());
296       default:
297         // The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
298         // Fortunately, it too has all the Y data up front, so we can read it.
299         if ("yuv420p".equals(previewFormatString)) {
300           return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
301             rect.width(), rect.height());
302         }
303     }
304     throw new IllegalArgumentException("Unsupported picture format: " +
305         previewFormat + '/' + previewFormatString);
306   }
307
308 }