6a01783d8cb07fccbf6a11e2ce0f30018c44aa7f
[zxing.git] / android / src / com / google / zxing / client / android / 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;
18
19 import com.google.zxing.ResultPoint;
20
21 import android.content.Context;
22 import android.graphics.Point;
23 import android.graphics.Rect;
24 import android.hardware.Camera;
25 import android.os.Handler;
26 import android.os.Message;
27 import android.util.Log;
28 import android.view.Display;
29 import android.view.SurfaceHolder;
30 import android.view.WindowManager;
31
32 import java.io.IOException;
33
34 /**
35  * This object wraps the Camera service object and expects to be the only one talking to it. The
36  * implementation encapsulates the steps needed to take preview-sized images, which are used for
37  * both preview and decoding.
38  */
39 final class CameraManager {
40
41   private static final String TAG = "CameraManager";
42
43   private static CameraManager mCameraManager;
44   private Camera mCamera;
45   private final Context mContext;
46   private Point mScreenResolution;
47   private Rect mFramingRect;
48   private Handler mPreviewHandler;
49   private int mPreviewMessage;
50   private Handler mAutoFocusHandler;
51   private int mAutoFocusMessage;
52   private boolean mInitialized;
53   private boolean mPreviewing;
54
55   public static void init(Context context) {
56     if (mCameraManager == null) {
57       mCameraManager = new CameraManager(context);
58     }
59   }
60
61   public static CameraManager get() {
62     return mCameraManager;
63   }
64
65   private CameraManager(Context context) {
66     mContext = context;
67     mCamera = null;
68     mInitialized = false;
69     mPreviewing = false;
70   }
71
72   public void openDriver(SurfaceHolder holder) throws IOException {
73     if (mCamera == null) {
74       mCamera = Camera.open();
75       mCamera.setPreviewDisplay(holder);
76
77       if (!mInitialized) {
78         mInitialized = true;
79         getScreenResolution();
80       }
81
82       setCameraParameters();
83     }
84   }
85
86   public void closeDriver() {
87     if (mCamera != null) {
88       mCamera.release();
89       mCamera = null;
90     }
91   }
92
93   public void startPreview() {
94     if (mCamera != null && !mPreviewing) {
95       mCamera.startPreview();
96       mPreviewing = true;
97     }
98   }
99
100   public void stopPreview() {
101     if (mCamera != null && mPreviewing) {
102       mCamera.setPreviewCallback(null);
103       mCamera.stopPreview();
104       mPreviewHandler = null;
105       mAutoFocusHandler = null;
106       mPreviewing = false;
107     }
108   }
109
110   /**
111    * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
112    * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
113    * respectively.
114    *
115    * @param handler The handler to send the message to.
116    * @param message The what field of the message to be sent.
117    */
118   public void requestPreviewFrame(Handler handler, int message) {
119     if (mCamera != null && mPreviewing) {
120       mPreviewHandler = handler;
121       mPreviewMessage = message;
122       mCamera.setOneShotPreviewCallback(previewCallback);
123     }
124   }
125
126   public void requestAutoFocus(Handler handler, int message) {
127     if (mCamera != null && mPreviewing) {
128       mAutoFocusHandler = handler;
129       mAutoFocusMessage = message;
130       mCamera.autoFocus(autoFocusCallback);
131     }
132   }
133
134   /**
135    * Calculates the framing rect which the UI should draw to show the user where to place the
136    * barcode. The actual captured image should be a bit larger than indicated because they might
137    * frame the shot too tightly. This target helps with alignment as well as forces the user to hold
138    * the device far enough away to ensure the image will be in focus.
139    *
140    * @return The rectangle to draw on screen in window coordinates.
141    */
142   public Rect getFramingRect() {
143     if (mFramingRect == null) {
144       int size = (mScreenResolution.x < mScreenResolution.y ? mScreenResolution.x :
145           mScreenResolution.y) * 3 / 4;
146       int leftOffset = (mScreenResolution.x - size) / 2;
147       int topOffset = (mScreenResolution.y - size) / 2;
148       mFramingRect = new Rect(leftOffset, topOffset, leftOffset + size, topOffset + size);
149       Log.v(TAG, "Calculated framing rect: " + mFramingRect);
150     }
151     return mFramingRect;
152   }
153
154   /**
155    * Converts the result points from still resolution coordinates to screen coordinates.
156    *
157    * @param points The points returned by the Reader subclass through Result.getResultPoints().
158    * @return An array of Points scaled to the size of the framing rect and offset appropriately
159    *         so they can be drawn in screen coordinates.
160    */
161   public Point[] convertResultPoints(ResultPoint[] points) {
162     Rect frame = getFramingRect();
163     int count = points.length;
164     Point[] output = new Point[count];
165     for (int x = 0; x < count; x++) {
166       output[x] = new Point();
167       output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
168       output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
169     }
170     return output;
171   }
172
173   /**
174    * Preview frames are delivered here, which we pass on to the registered handler. Make sure to
175    * clear the handler so it will only receive one message.
176    */
177   private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
178     public void onPreviewFrame(byte[] data, Camera camera) {
179       if (mPreviewHandler != null) {
180         Message message = mPreviewHandler.obtainMessage(mPreviewMessage, mScreenResolution.x,
181             mScreenResolution.y, data);
182         message.sendToTarget();
183         mPreviewHandler = null;
184       }
185     }
186   };
187
188   private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
189     public void onAutoFocus(boolean success, Camera camera) {
190       if (mAutoFocusHandler != null) {
191         Message message = mAutoFocusHandler.obtainMessage(mAutoFocusMessage, success);
192         // Simulate continuous autofocus by sending a focus request every 1.5 seconds.
193         mAutoFocusHandler.sendMessageDelayed(message, 1500L);
194         mAutoFocusHandler = null;
195       }
196     }
197   };
198
199   /**
200    * Sets the camera up to take preview images which are used for both preview and decoding. We're
201    * counting on the default YUV420 semi-planar data. If that changes in the future, we'll need to
202    * specify it explicitly with setPreviewFormat().
203    */
204   private void setCameraParameters() {
205     Camera.Parameters parameters = mCamera.getParameters();
206     parameters.setPreviewSize(mScreenResolution.x, mScreenResolution.y);
207
208     // FIXME: This is a hack to turn the flash off on the Samsung Galaxy. In the future there
209     // will hopefully be a standard setting like "off" that all devices will honor.
210     parameters.set("flash-mode", "2");
211     mCamera.setParameters(parameters);
212     Log.v(TAG, "Setting params for preview: width " + mScreenResolution.x + " height " +
213         mScreenResolution.y);
214   }
215
216   private Point getScreenResolution() {
217     if (mScreenResolution == null) {
218       WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
219       Display display = manager.getDefaultDisplay();
220       mScreenResolution = new Point(display.getWidth(), display.getHeight());
221     }
222     return mScreenResolution;
223   }
224
225 }