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