- Added Joseph's excellent supermarket checkout beep. There seems to be a bug in...
[zxing.git] / android-m3 / src / com / google / zxing / client / android / CameraManager.java
1 /*
2  * Copyright (C) 2008 Google Inc.
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 android.content.Context;
20 import android.graphics.Bitmap;
21 import android.graphics.Canvas;
22 import android.graphics.Point;
23 import android.graphics.Rect;
24 import android.hardware.CameraDevice;
25 import android.util.Log;
26 import android.view.Display;
27 import android.view.WindowManager;
28 import com.google.zxing.ResultPoint;
29
30 /**
31  * This object wraps the CameraDevice and expects to be the only one talking to it. The
32  * implementation encapsulates the steps needed to take preview-sized images and well as high
33  * resolution stills.
34  *
35  * @author dswitkin@google.com (Daniel Switkin)
36  */
37 final class CameraManager {
38
39   private static final String TAG = "CameraManager";
40
41   private final Context context;
42   private Point cameraResolution;
43   private Point stillResolution;
44   private Point previewResolution;
45   private int stillMultiplier;
46   private Point screenResolution;
47   private Rect framingRect;
48   private Bitmap bitmap;
49   private CameraDevice camera;
50   private final CameraDevice.CaptureParams params;
51   private boolean previewMode;
52   private boolean usePreviewForDecode;
53
54   CameraManager(Context context) {
55     this.context = context;
56     getScreenResolution();
57     calculateStillResolution();
58     calculatePreviewResolution();
59
60     usePreviewForDecode = true;
61     setUsePreviewForDecode(false);
62
63     camera = null;
64     params = new CameraDevice.CaptureParams();
65   }
66
67   public void openDriver() {
68     if (camera == null) {
69       camera = CameraDevice.open();
70       // If we're reopening the camera, we need to reset the capture params.
71       previewMode = false;
72       setPreviewMode(true);
73     }
74   }
75
76   public void closeDriver() {
77     if (camera != null) {
78       camera.close();
79       camera = null;
80     }
81   }
82
83   public void capturePreview(Canvas canvas) {
84     setPreviewMode(true);
85     camera.capture(canvas);
86   }
87
88   public Bitmap captureStill() {
89     setPreviewMode(usePreviewForDecode);
90     Canvas canvas = new Canvas(bitmap);
91     camera.capture(canvas);
92     return bitmap;
93   }
94
95   /**
96    * This method exists to help us evaluate how to best set up and use the camera.
97    * @param usePreview Decode at preview resolution if true, else use still resolution.
98    */
99   public void setUsePreviewForDecode(boolean usePreview) {
100     if (usePreviewForDecode != usePreview) {
101       usePreviewForDecode = usePreview;
102       if (usePreview) {
103         Log.v(TAG, "Creating bitmap at screen resolution: " + screenResolution.x + "," +
104             screenResolution.y);
105         bitmap = Bitmap.createBitmap(screenResolution.x, screenResolution.y, false);
106       } else {
107         Log.v(TAG, "Creating bitmap at still resolution: " + stillResolution.x + "," +
108             stillResolution.y);
109         bitmap = Bitmap.createBitmap(stillResolution.x, stillResolution.y, false);
110       }
111     }
112   }
113
114   /**
115    * Calculates the framing rect which the UI should draw to show the user where to place the
116    * barcode. The actual captured image should be a bit larger than indicated because they might
117    * frame the shot too tightly. This target helps with alignment as well as forces the user to hold
118    * the device far enough away to ensure the image will be in focus.
119    *
120    * @return The rectangle to draw on screen in window coordinates.
121    */
122   public Rect getFramingRect() {
123     if (framingRect == null) {
124       int size = stillResolution.x * screenResolution.x / previewResolution.x;
125       int leftOffset = (screenResolution.x - size) / 2;
126       int topOffset = (screenResolution.y - size) / 2;
127       framingRect = new Rect(leftOffset, topOffset, leftOffset + size, topOffset + size);
128       Log.v(TAG, "Calculated framing rect: " + framingRect);
129     }
130     return framingRect;
131   }
132
133   /**
134    * Converts the result points from still resolution coordinates to screen coordinates.
135    *
136    * @param points The points returned by the Reader subclass through Result.getResultPoints().
137    * @return An array of Points scaled to the size of the framing rect and offset appropriately
138    *         so they can be drawn in screen coordinates.
139    */
140   public Point[] convertResultPoints(ResultPoint[] points) {
141     Rect frame = getFramingRect();
142     int frameSize = frame.width();
143     int count = points.length;
144     Point[] output = new Point[count];
145     for (int x = 0; x < count; x++) {
146       output[x] = new Point();
147       if (usePreviewForDecode) {
148         output[x].x = (int) (points[x].getX() + 0.5f);
149         output[x].y = (int) (points[x].getY() + 0.5f);
150       } else {
151         output[x].x = frame.left + (int) (points[x].getX() * frameSize / stillResolution.x + 0.5f);
152         output[x].y = frame.top + (int) (points[x].getY() * frameSize / stillResolution.y + 0.5f);
153       }
154     }
155     return output;
156   }
157
158   /**
159    * Images for the live preview are taken at low resolution in RGB. The final stills for the
160    * decoding step are taken in YUV, since we only need the luminance channel. Other code depends
161    * on the ability to call this method for free if the correct mode is already set.
162    *
163    * @param on Setting on true will engage preview mode, setting it false will request still mode.
164    */
165   private void setPreviewMode(boolean on) {
166     if (on != previewMode) {
167       if (on) {
168         params.type = 1; // preview
169         params.srcWidth = previewResolution.x;
170         params.srcHeight = previewResolution.y;
171         params.leftPixel = (cameraResolution.x - params.srcWidth) / 2;
172         params.topPixel = (cameraResolution.y - params.srcHeight) / 2;
173         params.outputWidth = screenResolution.x;
174         params.outputHeight = screenResolution.y;
175         params.dataFormat = 2; // RGB565
176       } else {
177         params.type = 0; // still
178         params.srcWidth = stillResolution.x * stillMultiplier;
179         params.srcHeight = stillResolution.y * stillMultiplier;
180         params.leftPixel = (cameraResolution.x - params.srcWidth) / 2;
181         params.topPixel = (cameraResolution.y - params.srcHeight) / 2;
182         params.outputWidth = stillResolution.x;
183         params.outputHeight = stillResolution.y;
184         params.dataFormat = 2; // RGB565
185       }
186       String captureType = on ? "preview" : "still";
187       Log.v(TAG, "Setting params for " + captureType + ": srcWidth " + params.srcWidth +
188           " srcHeight " + params.srcHeight + " leftPixel " + params.leftPixel + " topPixel " +
189           params.topPixel + " outputWidth " + params.outputWidth + " outputHeight " +
190           params.outputHeight);
191       camera.setCaptureParams(params);
192       previewMode = on;
193     }
194   }
195
196   /**
197    * This method determines how to take the highest quality image (i.e. the one which has the best
198    * chance of being decoded) given the capabilities of the camera. It is a balancing act between
199    * having enough resolution to read UPCs and having few enough pixels to keep the QR Code
200    * processing fast. The result is the dimensions of the rectangle to capture from the center of
201    * the sensor, plus a stillMultiplier which indicates whether we'll ask the driver to downsample
202    * for us. This has the added benefit of keeping the memory footprint of the bitmap as small as
203    * possible.
204    */
205   private void calculateStillResolution() {
206     cameraResolution = getMaximumCameraResolution();
207     int minDimension = (cameraResolution.x < cameraResolution.y) ? cameraResolution.x :
208         cameraResolution.y;
209     int diagonalResolution = (int) Math.sqrt(cameraResolution.x * cameraResolution.x +
210         cameraResolution.y * cameraResolution.y);
211     float diagonalFov = getFieldOfView();
212
213     // Determine the field of view in the smaller dimension, then calculate how large an object
214     // would be at the minimum focus distance.
215     float fov = diagonalFov * minDimension / diagonalResolution;
216     double objectSize = Math.tan(Math.toRadians(fov / 2.0)) * getMinimumFocusDistance() * 2;
217
218     // Let's assume the largest barcode we might photograph at this distance is 3 inches across. By
219     // cropping to this size, we can avoid processing surrounding pixels, which helps with speed and
220     // accuracy. 
221     // TODO(dswitkin): Handle a device with a great macro mode where objectSize < 4 inches.
222     double crop = 3.0 / objectSize;
223     int nativeResolution = (int) (minDimension * crop);
224
225     // The camera driver can only capture images which are a multiple of eight, so it's necessary to
226     // round up.
227     nativeResolution = ((nativeResolution + 7) >> 3) << 3;
228     if (nativeResolution > minDimension) {
229       nativeResolution = minDimension;
230     }
231
232     // There's no point in capturing too much detail, so ask the driver to downsample. I haven't
233     // tried a non-integer multiple, but it seems unlikely to work.
234     double dpi = nativeResolution / objectSize;
235     stillMultiplier = 1;
236     if (dpi > 200) {
237       stillMultiplier = (int) (dpi / 200 + 1);
238     }
239     stillResolution = new Point(nativeResolution, nativeResolution);
240     Log.v(TAG, "FOV " + fov + " objectSize " + objectSize + " crop " + crop + " dpi " + dpi +
241         " nativeResolution " + nativeResolution + " stillMultiplier " + stillMultiplier);
242   }
243
244   /**
245    * The goal of the preview resolution is to show a little context around the framing rectangle
246    * which is the actual captured area in still mode.
247    */
248   private void calculatePreviewResolution() {
249     if (previewResolution == null) {
250       int previewHeight = (int) (stillResolution.x * stillMultiplier * 1.5f);
251       int previewWidth = previewHeight * screenResolution.x / screenResolution.y;
252       previewWidth = ((previewWidth + 7) >> 3) << 3;
253       if (previewWidth > cameraResolution.x) previewWidth = cameraResolution.x;
254       previewHeight = previewWidth * screenResolution.y / screenResolution.x;
255       previewResolution = new Point(previewWidth, previewHeight);
256       Log.v(TAG, "previewWidth " + previewWidth + " previewHeight " + previewHeight);
257     }
258   }
259
260   // FIXME(dswitkin): These three methods have temporary constants until the new Camera API can
261   // provide the real values for the current device.
262   // Temporary: the camera's maximum resolution in pixels.
263   private static Point getMaximumCameraResolution() {
264     return new Point(1280, 1024);
265   }
266
267   // Temporary: the diagonal field of view in degrees.
268   private static float getFieldOfView() {
269     return 60.0f;
270   }
271
272   // Temporary: the minimum focus distance in inches.
273   private static float getMinimumFocusDistance() {
274     return 12.0f;
275   }
276
277   private Point getScreenResolution() {
278     if (screenResolution == null) {
279       WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
280       Display display = manager.getDefaultDisplay();
281       screenResolution = new Point(display.getWidth(), display.getHeight());
282     }
283     return screenResolution;
284   }
285
286 }