Updates to build on M5
[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.BitmapFactory;
22 import android.graphics.Canvas;
23 import android.graphics.Point;
24 import android.graphics.Rect;
25 import android.hardware.CameraDevice;
26 import android.util.Log;
27 import android.view.Display;
28 import android.view.WindowManager;
29 import com.google.zxing.ResultPoint;
30 import com.tomgibara.android.camera.BitmapCamera;
31 import com.tomgibara.android.camera.CameraSource;
32
33 /**
34  * This object wraps the CameraDevice and expects to be the only one talking to it. The
35  * implementation encapsulates the steps needed to take preview-sized images and well as high
36  * resolution stills.
37  *
38  * @author dswitkin@google.com (Daniel Switkin)
39  */
40 final class CameraManager {
41
42   private static final String TAG = "CameraManager";
43
44   private final Context context;
45   private Point cameraResolution;
46   private Point stillResolution;
47   private int stillMultiplier;
48   private Point screenResolution;
49   private Rect framingRect;
50   private final Bitmap bitmap;
51   // TODO switch back to CameraDevice later
52   // private CameraDevice camera;
53   private CameraSource cameraSource;
54   // end TODO
55   private final CameraDevice.CaptureParams params;
56   private boolean previewMode;
57
58   CameraManager(Context context) {
59     this.context = context;
60     calculateStillResolution();
61     getScreenResolution();
62     bitmap = Bitmap.createBitmap(stillResolution.x, stillResolution.y, false);
63     // TODO switch back to CameraDevice later
64     // camera = CameraDevice.open();
65     Bitmap fakeBitmap = BitmapFactory.decodeFile("/tmp/barcode.jpg");
66     if (fakeBitmap == null) {
67       throw new RuntimeException("/tmp/barcode.jpg was not found");
68     }
69     cameraSource = new BitmapCamera(fakeBitmap, stillResolution.x, stillResolution.y);
70     // end TODO
71     params = new CameraDevice.CaptureParams();
72     previewMode = false;
73     setPreviewMode(true);
74   }
75
76   public void openDriver() {
77     // TODO switch back to CameraDevice later
78     // if (camera == null) {
79     //  camera = CameraDevice.open();
80     // }
81     // end TODO
82   }
83
84   public void closeDriver() {
85     // TODO switch back to CameraDevice later
86     // if (camera != null) {
87     //   camera.close();
88     //   camera = null;
89     // }
90     // end TODO
91   }
92
93   public void capturePreview(Canvas canvas) {
94     setPreviewMode(true);
95     // TODO switch back to CameraDevice later
96     // camera.capture(canvas);
97     cameraSource.capture(canvas);
98     // end TODO
99   }
100
101   public Bitmap captureStill() {
102     setPreviewMode(false);
103     Canvas canvas = new Canvas(bitmap);
104     // TODO switch back to CameraDevice later
105     // camera.capture(canvas);
106     cameraSource.capture(canvas);
107     // end TODO
108     return bitmap;
109   }
110
111   /**
112    * Calculates the framing rect which the UI should draw to show the user where to place the
113    * barcode. The actual captured image should be a bit larger than indicated because they might
114    * frame the shot too tightly. This target helps with alignment as well as forces the user to hold
115    * the device far enough away to ensure the image will be in focus.
116    *
117    * @return The rectangle to draw on screen in window coordinates.
118    */
119   public Rect getFramingRect() {
120     if (framingRect == null) {
121       int size = stillResolution.x * screenResolution.x / cameraResolution.x;
122       int leftOffset = (screenResolution.x - size) / 2;
123       int topOffset = (screenResolution.y - size) / 2;
124       framingRect = new Rect(leftOffset, topOffset, leftOffset + size, topOffset + size);
125     }
126     return framingRect;
127   }
128
129   /**
130    * Converts the result points from still resolution coordinates to screen coordinates.
131    *
132    * @param points The points returned by the Reader subclass through Result.getResultPoints().
133    * @return An array of Points scaled to the size of the framing rect and offset appropriately
134    *         so they can be drawn in screen coordinates.
135    */
136   public Point[] convertResultPoints(ResultPoint[] points) {
137     Rect frame = getFramingRect();
138     int frameSize = frame.width();
139     int count = points.length;
140     Point[] output = new Point[count];
141     for (int x = 0; x < count; x++) {
142       output[x] = new Point();
143       output[x].x = frame.left + (int) (points[x].getX() * frameSize / stillResolution.x + 0.5f);
144       output[x].y = frame.top + (int) (points[x].getY() * frameSize / stillResolution.y + 0.5f);
145     }
146     return output;
147   }
148
149   /**
150    * Images for the live preview are taken at low resolution in RGB. Other code depends
151    * on the ability to call this method for free if the correct mode is already set.
152    *
153    * @param on Setting on true will engage preview mode, setting it false will request still mode.
154    */
155   private void setPreviewMode(boolean on) {
156     if (on != previewMode) {
157       if (on) {
158         params.type = 1; // preview
159         if (cameraResolution.x / (float) cameraResolution.y <
160             screenResolution.x / (float) screenResolution.y) {
161           params.srcWidth = cameraResolution.x;
162           params.srcHeight = cameraResolution.x * screenResolution.y / screenResolution.x;
163           params.leftPixel = 0;
164           params.topPixel = (cameraResolution.y - params.srcHeight) / 2;
165         } else {
166           params.srcWidth = cameraResolution.y * screenResolution.x / screenResolution.y;
167           params.srcHeight = cameraResolution.y;
168           params.leftPixel = (cameraResolution.x - params.srcWidth) / 2;
169           params.topPixel = 0;
170         }
171         params.outputWidth = screenResolution.x;
172         params.outputHeight = screenResolution.y;
173         params.dataFormat = 2; // RGB565
174       } else {
175         params.type = 0; // still
176         params.srcWidth = stillResolution.x * stillMultiplier;
177         params.srcHeight = stillResolution.y * stillMultiplier;
178         params.leftPixel = (cameraResolution.x - params.srcWidth) / 2;
179         params.topPixel = (cameraResolution.y - params.srcHeight) / 2;
180         params.outputWidth = stillResolution.x;
181         params.outputHeight = stillResolution.y;
182         params.dataFormat = 2; // RGB565
183       }
184       String captureType = on ? "preview" : "still";
185       Log.v(TAG, "Setting params for " + captureType + ": srcWidth " + params.srcWidth +
186           " srcHeight " + params.srcHeight + " leftPixel " + params.leftPixel + " topPixel " +
187           params.topPixel + " outputWidth " + params.outputWidth + " outputHeight " +
188           params.outputHeight);
189       // TODO switch back to CameraDevice later
190       // camera.setCaptureParams(params);
191       // end TODO
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   // FIXME(dswitkin): These three methods have temporary constants until the new Camera API can
245   // provide the real values for the current device.
246   // Temporary: the camera's maximum resolution in pixels.
247   private static Point getMaximumCameraResolution() {
248     return new Point(1280, 1024);
249   }
250
251   // Temporary: the diagonal field of view in degrees.
252   private static float getFieldOfView() {
253     return 60.0f;
254   }
255
256   // Temporary: the minimum focus distance in inches.
257   private static float getMinimumFocusDistance() {
258     return 6.0f;
259   }
260
261   private Point getScreenResolution() {
262     if (screenResolution == null) {
263       WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
264       Display display = manager.getDefaultDisplay();
265       screenResolution = new Point(display.getWidth(), display.getHeight());
266     }
267     return screenResolution;
268   }
269
270 }