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