FocusOverlayManager.java revision fe44832abc2e9fb937ac5bd9c65e103397992e8c
1/*
2 * Copyright (C) 2012 The Android Open Source Project
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
17package com.android.camera;
18
19import android.annotation.TargetApi;
20import android.graphics.Matrix;
21import android.graphics.Rect;
22import android.graphics.RectF;
23import android.hardware.Camera.Area;
24import android.hardware.Camera.Parameters;
25import android.os.Handler;
26import android.os.Looper;
27import android.os.Message;
28import android.util.Log;
29
30import com.android.camera.ui.FaceView;
31import com.android.camera.ui.FocusIndicator;
32import com.android.camera.ui.PieRenderer;
33import com.android.gallery3d.common.ApiHelper;
34
35import java.util.ArrayList;
36import java.util.List;
37
38/* A class that handles everything about focus in still picture mode.
39 * This also handles the metering area because it is the same as focus area.
40 *
41 * The test cases:
42 * (1) The camera has continuous autofocus. Move the camera. Take a picture when
43 *     CAF is not in progress.
44 * (2) The camera has continuous autofocus. Move the camera. Take a picture when
45 *     CAF is in progress.
46 * (3) The camera has face detection. Point the camera at some faces. Hold the
47 *     shutter. Release to take a picture.
48 * (4) The camera has face detection. Point the camera at some faces. Single tap
49 *     the shutter to take a picture.
50 * (5) The camera has autofocus. Single tap the shutter to take a picture.
51 * (6) The camera has autofocus. Hold the shutter. Release to take a picture.
52 * (7) The camera has no autofocus. Single tap the shutter and take a picture.
53 * (8) The camera has autofocus and supports focus area. Touch the screen to
54 *     trigger autofocus. Take a picture.
55 * (9) The camera has autofocus and supports focus area. Touch the screen to
56 *     trigger autofocus. Wait until it times out.
57 * (10) The camera has no autofocus and supports metering area. Touch the screen
58 *     to change metering area.
59 */
60public class FocusOverlayManager {
61    private static final String TAG = "CAM_FocusManager";
62
63    private static final int RESET_TOUCH_FOCUS = 0;
64    private static final int RESET_TOUCH_FOCUS_DELAY = 3000;
65
66    private int mState = STATE_IDLE;
67    private static final int STATE_IDLE = 0; // Focus is not active.
68    private static final int STATE_FOCUSING = 1; // Focus is in progress.
69    // Focus is in progress and the camera should take a picture after focus finishes.
70    private static final int STATE_FOCUSING_SNAP_ON_FINISH = 2;
71    private static final int STATE_SUCCESS = 3; // Focus finishes and succeeds.
72    private static final int STATE_FAIL = 4; // Focus finishes and fails.
73
74    private boolean mInitialized;
75    private boolean mFocusAreaSupported;
76    private boolean mMeteringAreaSupported;
77    private boolean mLockAeAwbNeeded;
78    private boolean mAeAwbLock;
79    private Matrix mMatrix;
80
81    private PieRenderer mPieRenderer;
82
83    private int mPreviewWidth; // The width of the preview frame layout.
84    private int mPreviewHeight; // The height of the preview frame layout.
85    private boolean mMirror; // true if the camera is front-facing.
86    private int mDisplayOrientation;
87    private FaceView mFaceView;
88    private List<Object> mFocusArea; // focus area in driver format
89    private List<Object> mMeteringArea; // metering area in driver format
90    private String mFocusMode;
91    private String[] mDefaultFocusModes;
92    private String mOverrideFocusMode;
93    private Parameters mParameters;
94    private ComboPreferences mPreferences;
95    private Handler mHandler;
96    Listener mListener;
97
98    public interface Listener {
99        public void autoFocus();
100        public void cancelAutoFocus();
101        public boolean capture();
102        public void startFaceDetection();
103        public void stopFaceDetection();
104        public void setFocusParameters();
105    }
106
107    private class MainHandler extends Handler {
108        public MainHandler(Looper looper) {
109            super(looper);
110        }
111
112        @Override
113        public void handleMessage(Message msg) {
114            switch (msg.what) {
115                case RESET_TOUCH_FOCUS: {
116                    cancelAutoFocus();
117                    mListener.startFaceDetection();
118                    break;
119                }
120            }
121        }
122    }
123
124    public FocusOverlayManager(ComboPreferences preferences, String[] defaultFocusModes,
125            Parameters parameters, Listener listener,
126            boolean mirror, Looper looper) {
127        mHandler = new MainHandler(looper);
128        mMatrix = new Matrix();
129        mPreferences = preferences;
130        mDefaultFocusModes = defaultFocusModes;
131        setParameters(parameters);
132        mListener = listener;
133        setMirror(mirror);
134    }
135
136    public void setFocusRenderer(PieRenderer renderer) {
137        mPieRenderer = renderer;
138        mInitialized = (mMatrix != null);
139    }
140
141    public void setParameters(Parameters parameters) {
142        mParameters = parameters;
143        mFocusAreaSupported = Util.isFocusAreaSupported(parameters);
144        mMeteringAreaSupported = Util.isMeteringAreaSupported(parameters);
145        mLockAeAwbNeeded = (Util.isAutoExposureLockSupported(mParameters) ||
146                Util.isAutoWhiteBalanceLockSupported(mParameters));
147    }
148
149    public void setPreviewSize(int previewWidth, int previewHeight) {
150        if (mPreviewWidth != previewWidth || mPreviewHeight != previewHeight) {
151            mPreviewWidth = previewWidth;
152            mPreviewHeight = previewHeight;
153            setMatrix();
154        }
155    }
156
157    public void setMirror(boolean mirror) {
158        mMirror = mirror;
159        setMatrix();
160    }
161
162    public void setDisplayOrientation(int displayOrientation) {
163        mDisplayOrientation = displayOrientation;
164        setMatrix();
165    }
166
167    public void setFaceView(FaceView faceView) {
168        mFaceView = faceView;
169    }
170
171    private void setMatrix() {
172        if (mPreviewWidth != 0 && mPreviewHeight != 0) {
173            Matrix matrix = new Matrix();
174            Util.prepareMatrix(matrix, mMirror, mDisplayOrientation,
175                    mPreviewWidth, mPreviewHeight);
176            // In face detection, the matrix converts the driver coordinates to UI
177            // coordinates. In tap focus, the inverted matrix converts the UI
178            // coordinates to driver coordinates.
179            matrix.invert(mMatrix);
180            mInitialized = (mPieRenderer != null);
181        }
182    }
183
184    public void onShutterDown() {
185        if (!mInitialized) return;
186
187        // Lock AE and AWB so users can half-press shutter and recompose.
188        if (mLockAeAwbNeeded && !mAeAwbLock) {
189            mAeAwbLock = true;
190            mListener.setFocusParameters();
191        }
192
193        if (needAutoFocusCall()) {
194            // Do not focus if touch focus has been triggered.
195            if (mState != STATE_SUCCESS && mState != STATE_FAIL) {
196                autoFocus();
197            }
198        }
199    }
200
201    public void onShutterUp() {
202        if (!mInitialized) return;
203
204        if (needAutoFocusCall()) {
205            // User releases half-pressed focus key.
206            if (mState == STATE_FOCUSING || mState == STATE_SUCCESS
207                    || mState == STATE_FAIL) {
208                cancelAutoFocus();
209            }
210        }
211
212        // Unlock AE and AWB after cancelAutoFocus. Camera API does not
213        // guarantee setParameters can be called during autofocus.
214        if (mLockAeAwbNeeded && mAeAwbLock && (mState != STATE_FOCUSING_SNAP_ON_FINISH)) {
215            mAeAwbLock = false;
216            mListener.setFocusParameters();
217        }
218    }
219
220    public void doSnap() {
221        if (!mInitialized) return;
222
223        // If the user has half-pressed the shutter and focus is completed, we
224        // can take the photo right away. If the focus mode is infinity, we can
225        // also take the photo.
226        if (!needAutoFocusCall() || (mState == STATE_SUCCESS || mState == STATE_FAIL)) {
227            capture();
228        } else if (mState == STATE_FOCUSING) {
229            // Half pressing the shutter (i.e. the focus button event) will
230            // already have requested AF for us, so just request capture on
231            // focus here.
232            mState = STATE_FOCUSING_SNAP_ON_FINISH;
233        } else if (mState == STATE_IDLE) {
234            // We didn't do focus. This can happen if the user press focus key
235            // while the snapshot is still in progress. The user probably wants
236            // the next snapshot as soon as possible, so we just do a snapshot
237            // without focusing again.
238            capture();
239        }
240    }
241
242    public void onAutoFocus(boolean focused) {
243        if (mState == STATE_FOCUSING_SNAP_ON_FINISH) {
244            // Take the picture no matter focus succeeds or fails. No need
245            // to play the AF sound if we're about to play the shutter
246            // sound.
247            if (focused) {
248                mState = STATE_SUCCESS;
249            } else {
250                mState = STATE_FAIL;
251            }
252            updateFocusUI();
253            capture();
254        } else if (mState == STATE_FOCUSING) {
255            // This happens when (1) user is half-pressing the focus key or
256            // (2) touch focus is triggered. Play the focus tone. Do not
257            // take the picture now.
258            if (focused) {
259                mState = STATE_SUCCESS;
260            } else {
261                mState = STATE_FAIL;
262            }
263            updateFocusUI();
264            // If this is triggered by touch focus, cancel focus after a
265            // while.
266            if (mFocusArea != null) {
267                mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
268            }
269        } else if (mState == STATE_IDLE) {
270            // User has released the focus key before focus completes.
271            // Do nothing.
272        }
273    }
274
275    public void onAutoFocusMoving(boolean moving) {
276        if (!mInitialized) return;
277        // Ignore if the camera has detected some faces.
278        if (mFaceView != null && mFaceView.faceExists()) return;
279
280        // Ignore if we have requested autofocus. This method only handles
281        // continuous autofocus.
282        if (mState != STATE_IDLE) return;
283
284        if (moving) {
285            mPieRenderer.showStart();
286        } else {
287            mPieRenderer.showSuccess(true);
288        }
289    }
290
291    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
292    private void initializeFocusAreas(int focusWidth, int focusHeight,
293            int x, int y, int previewWidth, int previewHeight) {
294        if (mFocusArea == null) {
295            mFocusArea = new ArrayList<Object>();
296            mFocusArea.add(new Area(new Rect(), 1));
297        }
298
299        // Convert the coordinates to driver format.
300        calculateTapArea(focusWidth, focusHeight, 1f, x, y, previewWidth, previewHeight,
301                ((Area) mFocusArea.get(0)).rect);
302    }
303
304    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
305    private void initializeMeteringAreas(int focusWidth, int focusHeight,
306            int x, int y, int previewWidth, int previewHeight) {
307        if (mMeteringArea == null) {
308            mMeteringArea = new ArrayList<Object>();
309            mMeteringArea.add(new Area(new Rect(), 1));
310        }
311
312        // Convert the coordinates to driver format.
313        // AE area is bigger because exposure is sensitive and
314        // easy to over- or underexposure if area is too small.
315        calculateTapArea(focusWidth, focusHeight, 1.5f, x, y, previewWidth, previewHeight,
316                ((Area) mMeteringArea.get(0)).rect);
317    }
318
319    public void onSingleTapUp(int x, int y) {
320        if (!mInitialized || mState == STATE_FOCUSING_SNAP_ON_FINISH) return;
321
322        // Let users be able to cancel previous touch focus.
323        if ((mFocusArea != null) && (mState == STATE_FOCUSING ||
324                    mState == STATE_SUCCESS || mState == STATE_FAIL)) {
325            cancelAutoFocus();
326        }
327        // Initialize variables.
328        int focusWidth = mPieRenderer.getSize();
329        int focusHeight = mPieRenderer.getSize();
330        if (focusWidth == 0 || mPieRenderer.getWidth() == 0
331                || mPieRenderer.getHeight() == 0) return;
332        int previewWidth = mPreviewWidth;
333        int previewHeight = mPreviewHeight;
334        // Initialize mFocusArea.
335        if (mFocusAreaSupported) {
336            initializeFocusAreas(
337                    focusWidth, focusHeight, x, y, previewWidth, previewHeight);
338        }
339        // Initialize mMeteringArea.
340        if (mMeteringAreaSupported) {
341            initializeMeteringAreas(
342                    focusWidth, focusHeight, x, y, previewWidth, previewHeight);
343        }
344
345        // Use margin to set the focus indicator to the touched area.
346        mPieRenderer.setFocus(x, y, false);
347
348        // Stop face detection because we want to specify focus and metering area.
349        mListener.stopFaceDetection();
350
351        // Set the focus area and metering area.
352        mListener.setFocusParameters();
353        if (mFocusAreaSupported) {
354            autoFocus();
355        } else {  // Just show the indicator in all other cases.
356            updateFocusUI();
357            // Reset the metering area in 3 seconds.
358            mHandler.removeMessages(RESET_TOUCH_FOCUS);
359            mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
360        }
361    }
362
363    public void onPreviewStarted() {
364        mState = STATE_IDLE;
365    }
366
367    public void onPreviewStopped() {
368        mState = STATE_IDLE;
369        resetTouchFocus();
370        // If auto focus was in progress, it would have been canceled.
371        updateFocusUI();
372    }
373
374    public void onCameraReleased() {
375        onPreviewStopped();
376    }
377
378    private void autoFocus() {
379        Log.v(TAG, "Start autofocus.");
380        mListener.autoFocus();
381        mState = STATE_FOCUSING;
382        // Pause the face view because the driver will keep sending face
383        // callbacks after the focus completes.
384        if (mFaceView != null) mFaceView.pause();
385        updateFocusUI();
386        mHandler.removeMessages(RESET_TOUCH_FOCUS);
387    }
388
389    private void cancelAutoFocus() {
390        Log.v(TAG, "Cancel autofocus.");
391
392        // Reset the tap area before calling mListener.cancelAutofocus.
393        // Otherwise, focus mode stays at auto and the tap area passed to the
394        // driver is not reset.
395        resetTouchFocus();
396        mListener.cancelAutoFocus();
397        if (mFaceView != null) mFaceView.resume();
398        mState = STATE_IDLE;
399        updateFocusUI();
400        mHandler.removeMessages(RESET_TOUCH_FOCUS);
401    }
402
403    private void capture() {
404        if (mListener.capture()) {
405            mState = STATE_IDLE;
406            mHandler.removeMessages(RESET_TOUCH_FOCUS);
407        }
408    }
409
410    public String getFocusMode() {
411        if (mOverrideFocusMode != null) return mOverrideFocusMode;
412        List<String> supportedFocusModes = mParameters.getSupportedFocusModes();
413
414        if (mFocusAreaSupported && mFocusArea != null) {
415            // Always use autofocus in tap-to-focus.
416            mFocusMode = Parameters.FOCUS_MODE_AUTO;
417        } else {
418            // The default is continuous autofocus.
419            mFocusMode = mPreferences.getString(
420                    CameraSettings.KEY_FOCUS_MODE, null);
421
422            // Try to find a supported focus mode from the default list.
423            if (mFocusMode == null) {
424                for (int i = 0; i < mDefaultFocusModes.length; i++) {
425                    String mode = mDefaultFocusModes[i];
426                    if (Util.isSupported(mode, supportedFocusModes)) {
427                        mFocusMode = mode;
428                        break;
429                    }
430                }
431            }
432        }
433        if (!Util.isSupported(mFocusMode, supportedFocusModes)) {
434            // For some reasons, the driver does not support the current
435            // focus mode. Fall back to auto.
436            if (Util.isSupported(Parameters.FOCUS_MODE_AUTO,
437                    mParameters.getSupportedFocusModes())) {
438                mFocusMode = Parameters.FOCUS_MODE_AUTO;
439            } else {
440                mFocusMode = mParameters.getFocusMode();
441            }
442        }
443        return mFocusMode;
444    }
445
446    public List getFocusAreas() {
447        return mFocusArea;
448    }
449
450    public List getMeteringAreas() {
451        return mMeteringArea;
452    }
453
454    public void updateFocusUI() {
455        if (!mInitialized) return;
456        // Show only focus indicator or face indicator.
457        boolean faceExists = (mFaceView != null && mFaceView.faceExists());
458        FocusIndicator focusIndicator = (faceExists) ? mFaceView : mPieRenderer;
459
460        if (mState == STATE_IDLE) {
461            if (mFocusArea == null) {
462                focusIndicator.clear();
463            } else {
464                // Users touch on the preview and the indicator represents the
465                // metering area. Either focus area is not supported or
466                // autoFocus call is not required.
467                focusIndicator.showStart();
468            }
469        } else if (mState == STATE_FOCUSING || mState == STATE_FOCUSING_SNAP_ON_FINISH) {
470            focusIndicator.showStart();
471        } else {
472            if (Util.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusMode)) {
473                // TODO: check HAL behavior and decide if this can be removed.
474                focusIndicator.showSuccess(false);
475            } else if (mState == STATE_SUCCESS) {
476                focusIndicator.showSuccess(false);
477            } else if (mState == STATE_FAIL) {
478                focusIndicator.showFail(false);
479            }
480        }
481    }
482
483    public void resetTouchFocus() {
484        if (!mInitialized) return;
485
486        // Put focus indicator to the center. clear reset position
487        mPieRenderer.clear();
488
489        mFocusArea = null;
490        mMeteringArea = null;
491    }
492
493    private void calculateTapArea(int focusWidth, int focusHeight, float areaMultiple,
494            int x, int y, int previewWidth, int previewHeight, Rect rect) {
495        int areaWidth = (int) (focusWidth * areaMultiple);
496        int areaHeight = (int) (focusHeight * areaMultiple);
497        int left = Util.clamp(x - areaWidth / 2, 0, previewWidth - areaWidth);
498        int top = Util.clamp(y - areaHeight / 2, 0, previewHeight - areaHeight);
499
500        RectF rectF = new RectF(left, top, left + areaWidth, top + areaHeight);
501        mMatrix.mapRect(rectF);
502        Util.rectFToRect(rectF, rect);
503    }
504
505    /* package */ int getFocusState() {
506        return mState;
507    }
508
509    public boolean isFocusCompleted() {
510        return mState == STATE_SUCCESS || mState == STATE_FAIL;
511    }
512
513    public boolean isFocusingSnapOnFinish() {
514        return mState == STATE_FOCUSING_SNAP_ON_FINISH;
515    }
516
517    public void removeMessages() {
518        mHandler.removeMessages(RESET_TOUCH_FOCUS);
519    }
520
521    public void overrideFocusMode(String focusMode) {
522        mOverrideFocusMode = focusMode;
523    }
524
525    public void setAeAwbLock(boolean lock) {
526        mAeAwbLock = lock;
527    }
528
529    public boolean getAeAwbLock() {
530        return mAeAwbLock;
531    }
532
533    private boolean needAutoFocusCall() {
534        String focusMode = getFocusMode();
535        return !(focusMode.equals(Parameters.FOCUS_MODE_INFINITY)
536                || focusMode.equals(Parameters.FOCUS_MODE_FIXED)
537                || focusMode.equals(Parameters.FOCUS_MODE_EDOF));
538    }
539}
540