CaptureModule.java revision 4de9b72f79fe256766f25497bff44cb5533b7508
1/*
2 * Copyright (C) 2014 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.app.Activity;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.graphics.Bitmap;
23import android.graphics.Matrix;
24import android.graphics.RectF;
25import android.graphics.SurfaceTexture;
26import android.hardware.Sensor;
27import android.hardware.SensorEvent;
28import android.hardware.SensorEventListener;
29import android.hardware.SensorManager;
30import android.location.Location;
31import android.net.Uri;
32import android.os.Handler;
33import android.os.HandlerThread;
34import android.os.SystemClock;
35import android.provider.MediaStore;
36import android.view.KeyEvent;
37import android.view.OrientationEventListener;
38import android.view.Surface;
39import android.view.TextureView;
40import android.view.View;
41import android.view.View.OnLayoutChangeListener;
42
43import com.android.camera.app.AppController;
44import com.android.camera.app.CameraAppUI;
45import com.android.camera.app.CameraAppUI.BottomBarUISpec;
46import com.android.camera.app.LocationManager;
47import com.android.camera.app.MediaSaver;
48import com.android.camera.debug.DebugPropertyHelper;
49import com.android.camera.debug.Log;
50import com.android.camera.debug.Log.Tag;
51import com.android.camera.hardware.HardwareSpec;
52import com.android.camera.module.ModuleController;
53import com.android.camera.one.OneCamera;
54import com.android.camera.one.OneCamera.AutoFocusState;
55import com.android.camera.one.OneCamera.CaptureReadyCallback;
56import com.android.camera.one.OneCamera.Facing;
57import com.android.camera.one.OneCamera.OpenCallback;
58import com.android.camera.one.OneCamera.PhotoCaptureParameters;
59import com.android.camera.one.OneCamera.PhotoCaptureParameters.Flash;
60import com.android.camera.one.OneCameraManager;
61import com.android.camera.one.Settings3A;
62import com.android.camera.one.v2.OneCameraManagerImpl;
63import com.android.camera.remote.RemoteCameraModule;
64import com.android.camera.session.CaptureSession;
65import com.android.camera.settings.Keys;
66import com.android.camera.settings.SettingsManager;
67import com.android.camera.ui.CountDownView;
68import com.android.camera.ui.PreviewStatusListener;
69import com.android.camera.ui.TouchCoordinate;
70import com.android.camera.util.CameraUtil;
71import com.android.camera.util.GcamHelper;
72import com.android.camera.util.Size;
73import com.android.camera.util.UsageStatistics;
74import com.android.camera2.R;
75import com.android.ex.camera2.portability.CameraAgent.CameraProxy;
76
77import java.io.File;
78import java.util.concurrent.Semaphore;
79import java.util.concurrent.TimeUnit;
80
81/**
82 * New Capture module that is made to support photo and video capture on top of
83 * the OneCamera API, to transparently support GCam.
84 * <p>
85 * This has been a re-write with pieces taken and improved from GCamModule and
86 * PhotoModule, which are to be retired eventually.
87 * <p>
88 * TODO:
89 * <ul>
90 * <li>Server-side logging
91 * <li>Focusing (managed by OneCamera implementations)
92 * <li>Show location dialog on first start
93 * <li>Show resolution dialog on certain devices
94 * <li>Store location
95 * <li>Capture intent
96 * </ul>
97 */
98public class CaptureModule extends CameraModule
99        implements MediaSaver.QueueListener,
100        ModuleController,
101        CountDownView.OnCountDownStatusListener,
102        OneCamera.PictureCallback,
103        OneCamera.FocusStateListener,
104        OneCamera.ReadyStateChangedListener,
105        PreviewStatusListener.PreviewAreaChangedListener,
106        RemoteCameraModule,
107        SensorEventListener,
108        SettingsManager.OnSettingChangedListener,
109        TextureView.SurfaceTextureListener {
110
111    /**
112     * Called on layout changes.
113     */
114    private final OnLayoutChangeListener mLayoutListener = new OnLayoutChangeListener() {
115        @Override
116        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
117                int oldTop, int oldRight, int oldBottom) {
118            int width = right - left;
119            int height = bottom - top;
120            updatePreviewTransform(width, height, false);
121        }
122    };
123
124    /**
125     * Hide AF target UI element.
126     */
127    Runnable mHideAutoFocusTargetRunnable = new Runnable() {
128        @Override
129        public void run() {
130            // For debug UI off, showAutoFocusSuccess() just hides the AF UI.
131            if (mFocusedAtEnd) {
132                mUI.showAutoFocusSuccess();
133            } else {
134                mUI.showAutoFocusFailure();
135            }
136        }
137    };
138
139    private static final Tag TAG = new Tag("CaptureModule");
140    private static final String PHOTO_MODULE_STRING_ID = "PhotoModule";
141    /** Enable additional debug output. */
142    private static final boolean DEBUG = true;
143
144    /** Timeout for camera open/close operations. */
145    private static final int CAMERA_OPEN_CLOSE_TIMEOUT_MILLIS = 2500;
146
147    /** System Properties switch to enable debugging focus UI. */
148    private static final boolean CAPTURE_DEBUG_UI = DebugPropertyHelper.showCaptureDebugUI();
149
150    private final Object mDimensionLock = new Object();
151
152    /**
153     * Sticky Gcam mode is when this module's sole purpose it to be the Gcam
154     * mode. If true, the device uses {@link PhotoModule} for normal picture
155     * taking.
156     */
157    private final boolean mStickyGcamCamera;
158
159    /**
160     * Lock for race conditions in the SurfaceTextureListener callbacks.
161     */
162    private final Object mSurfaceLock = new Object();
163    /** Controller giving us access to other services. */
164    private final AppController mAppController;
165    /** The applications settings manager. */
166    private final SettingsManager mSettingsManager;
167    /** Application context. */
168    private final Context mContext;
169    private CaptureModuleUI mUI;
170    /** The camera manager used to open cameras. */
171    private OneCameraManager mCameraManager;
172    /** The currently opened camera device, or null if the camera is closed. */
173    private OneCamera mCamera;
174    /** Held when opening or closing the camera. */
175    private final Semaphore mCameraOpenCloseLock = new Semaphore(1);
176    /** The direction the currently opened camera is facing to. */
177    private Facing mCameraFacing = Facing.BACK;
178    /** Whether HDR is currently enabled. */
179    private boolean mHdrEnabled = false;
180
181    /** The texture used to render the preview in. */
182    private SurfaceTexture mPreviewTexture;
183
184    /** State by the module state machine. */
185    private static enum ModuleState {
186        IDLE,
187        WATCH_FOR_NEXT_FRAME_AFTER_PREVIEW_STARTED,
188        UPDATE_TRANSFORM_ON_NEXT_SURFACE_TEXTURE_UPDATE,
189    }
190
191    /** The current state of the module. */
192    private ModuleState mState = ModuleState.IDLE;
193    /** Current orientation of the device. */
194    private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
195    /** Current zoom value. */
196    private float mZoomValue = 1f;
197    /** Current duration of capture timer in seconds. */
198    private int mTimerDuration;
199    // TODO: Get image capture intent UI working.
200    private boolean mIsImageCaptureIntent;
201
202    /** True if in AF tap-to-focus sequence. */
203    private boolean mTapToFocusWaitForActiveScan = false;
204    /** Records beginning frame of each AF scan. */
205    private long mAutoFocusScanStartFrame = -1;
206    /** Records beginning time of each AF scan in uptimeMillis. */
207    private long mAutoFocusScanStartTime;
208
209    /** Persistence of Tap to Focus target UI after scan complete. */
210    private static final int FOCUS_HOLD_UI_MILLIS = 0;
211    /** Worst case persistence of TTF target UI. */
212    private static final int FOCUS_UI_TIMEOUT_MILLIS = 2000;
213    /** Results from last tap to focus scan */
214    private boolean mFocusedAtEnd;
215    /** Sensor manager we use to get the heading of the device. */
216    private SensorManager mSensorManager;
217    /** Accelerometer. */
218    private Sensor mAccelerometerSensor;
219    /** Compass. */
220    private Sensor mMagneticSensor;
221
222    /** Accelerometer data. */
223    private final float[] mGData = new float[3];
224    /** Magnetic sensor data. */
225    private final float[] mMData = new float[3];
226    /** Temporary rotation matrix. */
227    private final float[] mR = new float[16];
228    /** Current compass heading. */
229    private int mHeading = -1;
230
231    /** Used to fetch and embed the location into captured images. */
232    private LocationManager mLocationManager;
233    /** Plays sounds for countdown timer. */
234    private SoundPlayer mCountdownSoundPlayer;
235
236    /** Whether the module is paused right now. */
237    private boolean mPaused;
238
239    /** Main thread handler. */
240    private Handler mMainHandler;
241    /** Handler thread for camera-related operations. */
242    private Handler mCameraHandler;
243
244    /** Current display rotation in degrees. */
245    private int mDisplayRotation;
246    /** Current screen width in pixels. */
247    private int mScreenWidth;
248    /** Current screen height in pixels. */
249    private int mScreenHeight;
250    /** Current width of preview frames from camera. */
251    private int mPreviewBufferWidth;
252    /** Current height of preview frames from camera.. */
253    private int mPreviewBufferHeight;
254    /** Area used by preview. */
255    RectF mPreviewArea;
256
257    /** The current preview transformation matrix. */
258    private Matrix mPreviewTranformationMatrix = new Matrix();
259    /** TODO: This is N5 specific. */
260    public static final float FULLSCREEN_ASPECT_RATIO = 16 / 9f;
261
262    /** A directory to store debug information in during development. */
263    private final File mDebugDataDir;
264
265    /** CLEAN UP START */
266    // private boolean mFirstLayout;
267    // private int[] mTargetFPSRanges;
268    // private float mZoomValue;
269    // private int mSensorOrientation;
270    // private int mLensFacing;
271    // private String mFlashMode;
272    /** CLEAN UP END */
273
274    public CaptureModule(AppController appController) {
275        this(appController, false);
276    }
277
278    /** Constructs a new capture module. */
279    public CaptureModule(AppController appController, boolean stickyHdr) {
280        super(appController);
281        mAppController = appController;
282        mContext = mAppController.getAndroidContext();
283        mSettingsManager = mAppController.getSettingsManager();
284        mSettingsManager.addListener(this);
285        mDebugDataDir = mContext.getExternalCacheDir();
286        mStickyGcamCamera = stickyHdr;
287    }
288
289    @Override
290    public void init(CameraActivity activity, boolean isSecureCamera, boolean isCaptureIntent) {
291        Log.d(TAG, "init");
292        mMainHandler = new Handler(activity.getMainLooper());
293        HandlerThread thread = new HandlerThread("CaptureModule.mCameraHandler");
294        thread.start();
295        mCameraHandler = new Handler(thread.getLooper());
296        mCameraManager = mAppController.getCameraManager();
297        mLocationManager = mAppController.getLocationManager();
298        mDisplayRotation = CameraUtil.getDisplayRotation(mContext);
299        mCameraFacing = getFacingFromCameraId(mSettingsManager.getInteger(
300                mAppController.getModuleScope(),
301                Keys.KEY_CAMERA_ID));
302        mUI = new CaptureModuleUI(activity, this, mAppController.getModuleLayoutRoot(),
303                mLayoutListener);
304        mAppController.setPreviewStatusListener(mUI);
305        mPreviewTexture = mAppController.getCameraAppUI().getSurfaceTexture();
306        mSensorManager = (SensorManager) (mContext.getSystemService(Context.SENSOR_SERVICE));
307        mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
308        mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
309        mCountdownSoundPlayer = new SoundPlayer(mContext);
310
311        String action = activity.getIntent().getAction();
312        mIsImageCaptureIntent = (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)
313                || CameraActivity.ACTION_IMAGE_CAPTURE_SECURE.equals(action));
314        View cancelButton = activity.findViewById(R.id.shutter_cancel_button);
315        cancelButton.setOnClickListener(new View.OnClickListener() {
316            @Override
317            public void onClick(View view) {
318                cancelCountDown();
319            }
320        });
321    }
322
323    @Override
324    public void onShutterButtonFocus(boolean pressed) {
325        // TODO Auto-generated method stub
326    }
327
328    @Override
329    public void onShutterCoordinate(TouchCoordinate coord) {
330        // TODO Auto-generated method stub
331    }
332
333    @Override
334    public void onShutterButtonClick() {
335        if (mCamera == null) {
336            return;
337        }
338
339        int countDownDuration = mSettingsManager
340                .getInteger(SettingsManager.SCOPE_GLOBAL, Keys.KEY_COUNTDOWN_DURATION);
341        mTimerDuration = countDownDuration;
342        if (countDownDuration > 0) {
343            // Start count down.
344            mAppController.getCameraAppUI().transitionToCancel();
345            mAppController.getCameraAppUI().hideModeOptions();
346            mUI.setCountdownFinishedListener(this);
347            mUI.startCountdown(countDownDuration);
348            // Will take picture later via listener callback.
349        } else {
350            takePictureNow();
351        }
352    }
353
354    private void takePictureNow() {
355        Location location = mLocationManager.getCurrentLocation();
356
357        // Set up the capture session.
358        long sessionTime = System.currentTimeMillis();
359        String title = CameraUtil.createJpegName(sessionTime);
360        CaptureSession session = getServices().getCaptureSessionManager()
361                .createNewSession(title, sessionTime, location);
362
363        // Set up the parameters for this capture.
364        PhotoCaptureParameters params = new PhotoCaptureParameters();
365        params.title = title;
366        params.callback = this;
367        params.orientation = getOrientation();
368        params.flashMode = getFlashModeFromSettings();
369        params.heading = mHeading;
370        params.debugDataFolder = mDebugDataDir;
371        params.location = location;
372
373        mCamera.takePicture(params, session);
374    }
375
376    @Override
377    public void onCountDownFinished() {
378        if (mIsImageCaptureIntent) {
379            mAppController.getCameraAppUI().transitionToIntentReviewLayout();
380        } else {
381            mAppController.getCameraAppUI().transitionToCapture();
382        }
383        mAppController.getCameraAppUI().showModeOptions();
384        if (mPaused) {
385            return;
386        }
387        takePictureNow();
388    }
389
390    @Override
391    public void onRemainingSecondsChanged(int remainingSeconds) {
392        if (remainingSeconds == 1) {
393            mCountdownSoundPlayer.play(R.raw.timer_final_second, 0.6f);
394        } else if (remainingSeconds == 2 || remainingSeconds == 3) {
395            mCountdownSoundPlayer.play(R.raw.timer_increment, 0.6f);
396        }
397    }
398
399    private void cancelCountDown() {
400        if (mUI.isCountingDown()) {
401            // Cancel on-going countdown.
402            mUI.cancelCountDown();
403        }
404        mAppController.getCameraAppUI().showModeOptions();
405        mAppController.getCameraAppUI().transitionToCapture();
406    }
407
408    @Override
409    public void onQuickExpose() {
410        mMainHandler.post(new Runnable() {
411            @Override
412            public void run() {
413                // Starts the short version of the capture animation UI.
414                mAppController.startPreCaptureAnimation(true);
415            }
416        });
417    }
418
419    @Override
420    public void onPreviewAreaChanged(RectF previewArea) {
421        mPreviewArea = previewArea;
422        mUI.onPreviewAreaChanged(previewArea);
423        // mUI.updatePreviewAreaRect(previewArea);
424        mUI.positionProgressOverlay(previewArea);
425    }
426
427    @Override
428    public void onSensorChanged(SensorEvent event) {
429        // This is literally the same as the GCamModule implementation.
430        int type = event.sensor.getType();
431        float[] data;
432        if (type == Sensor.TYPE_ACCELEROMETER) {
433            data = mGData;
434        } else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
435            data = mMData;
436        } else {
437            Log.w(TAG, String.format("Unexpected sensor type %s", event.sensor.getName()));
438            return;
439        }
440        for (int i = 0; i < 3; i++) {
441            data[i] = event.values[i];
442        }
443        float[] orientation = new float[3];
444        SensorManager.getRotationMatrix(mR, null, mGData, mMData);
445        SensorManager.getOrientation(mR, orientation);
446        mHeading = (int) (orientation[0] * 180f / Math.PI) % 360;
447
448        if (mHeading < 0) {
449            mHeading += 360;
450        }
451    }
452
453    @Override
454    public void onAccuracyChanged(Sensor sensor, int accuracy) {
455        // TODO Auto-generated method stub
456    }
457
458    @Override
459    public void onQueueStatus(boolean full) {
460        // TODO Auto-generated method stub
461    }
462
463    @Override
464    public void onRemoteShutterPress() {
465        // TODO: Check whether shutter is enabled.
466        onShutterButtonClick();
467    }
468
469    @Override
470    public void onSurfaceTextureAvailable(final SurfaceTexture surface, int width, int height) {
471        Log.d(TAG, "onSurfaceTextureAvailable");
472        // Force to re-apply transform matrix here as a workaround for
473        // b/11168275
474        updatePreviewTransform(width, height, true);
475        initSurface(surface);
476    }
477
478    public void initSurface(final SurfaceTexture surface) {
479        mPreviewTexture = surface;
480        closeCamera();
481        openCameraAndStartPreview();
482    }
483
484    @Override
485    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
486        Log.d(TAG, "onSurfaceTextureSizeChanged");
487        resetDefaultBufferSize();
488    }
489
490    @Override
491    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
492        Log.d(TAG, "onSurfaceTextureDestroyed");
493        mPreviewTexture = null;
494        closeCamera();
495        return true;
496    }
497
498    @Override
499    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
500        if (mState == ModuleState.UPDATE_TRANSFORM_ON_NEXT_SURFACE_TEXTURE_UPDATE) {
501            Log.d(TAG, "onSurfaceTextureUpdated --> updatePreviewTransform");
502            mState = ModuleState.IDLE;
503            CameraAppUI appUI = mAppController.getCameraAppUI();
504            updatePreviewTransform(appUI.getSurfaceWidth(), appUI.getSurfaceHeight(), true);
505        }
506    }
507
508    @Override
509    public String getModuleStringIdentifier() {
510        return PHOTO_MODULE_STRING_ID;
511    }
512
513    @Override
514    public void resume() {
515        mPaused = false;
516        mAppController.getCameraAppUI().onChangeCamera();
517        mAppController.addPreviewAreaSizeChangedListener(this);
518        resetDefaultBufferSize();
519        getServices().getRemoteShutterListener().onModuleReady(this);
520        // TODO: Check if we can really take a photo right now (memory, camera
521        // state, ... ).
522        mAppController.getCameraAppUI().enableModeOptions();
523        mAppController.setShutterEnabled(true);
524
525        // Get events from the accelerometer and magnetic sensor.
526        if (mAccelerometerSensor != null) {
527            mSensorManager.registerListener(this, mAccelerometerSensor,
528                    SensorManager.SENSOR_DELAY_NORMAL);
529        }
530        if (mMagneticSensor != null) {
531            mSensorManager.registerListener(this, mMagneticSensor,
532                    SensorManager.SENSOR_DELAY_NORMAL);
533        }
534        mHdrEnabled = mStickyGcamCamera || mAppController.getSettingsManager().getInteger(
535                SettingsManager.SCOPE_GLOBAL, Keys.KEY_CAMERA_HDR_PLUS) == 1;
536
537        // This means we are resuming with an existing preview texture. This
538        // means we will never get the onSurfaceTextureAvailable call. So we
539        // have to open the camera and start the preview here.
540        if (mPreviewTexture != null) {
541            initSurface(mPreviewTexture);
542        }
543
544        mCountdownSoundPlayer.loadSound(R.raw.timer_final_second);
545        mCountdownSoundPlayer.loadSound(R.raw.timer_increment);
546    }
547
548    @Override
549    public void pause() {
550        mPaused = true;
551        cancelCountDown();
552        resetTextureBufferSize();
553        closeCamera();
554        mCountdownSoundPlayer.unloadSound(R.raw.timer_final_second);
555        mCountdownSoundPlayer.unloadSound(R.raw.timer_increment);
556        // Remove delayed resume trigger, if it hasn't been executed yet.
557        mMainHandler.removeCallbacksAndMessages(null);
558
559        // Unregister the sensors.
560        if (mAccelerometerSensor != null) {
561            mSensorManager.unregisterListener(this, mAccelerometerSensor);
562        }
563        if (mMagneticSensor != null) {
564            mSensorManager.unregisterListener(this, mMagneticSensor);
565        }
566    }
567
568    @Override
569    public void destroy() {
570        mCountdownSoundPlayer.release();
571        mCameraHandler.getLooper().quitSafely();
572    }
573
574    @Override
575    public void onLayoutOrientationChanged(boolean isLandscape) {
576        Log.d(TAG, "onLayoutOrientationChanged");
577    }
578
579    @Override
580    public void onOrientationChanged(int orientation) {
581        // We keep the last known orientation. So if the user first orient
582        // the camera then point the camera to floor or sky, we still have
583        // the correct orientation.
584        if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
585            return;
586        }
587
588        // TODO: Document orientation compute logic and unify them in OrientationManagerImpl.
589        // b/17443789
590        // Flip to counter-clockwise orientation.
591        mOrientation = (360 - orientation) % 360;
592    }
593
594    @Override
595    public void onCameraAvailable(CameraProxy cameraProxy) {
596        // Ignore since we manage the camera ourselves until we remove this.
597    }
598
599    @Override
600    public void hardResetSettings(SettingsManager settingsManager) {
601        if (mStickyGcamCamera) {
602            // Sitcky HDR+ mode should hard reset HDR+ to on, and camera back
603            // facing.
604            settingsManager.set(SettingsManager.SCOPE_GLOBAL, Keys.KEY_CAMERA_HDR_PLUS, true);
605            settingsManager.set(mAppController.getModuleScope(), Keys.KEY_CAMERA_ID,
606                    getBackFacingCameraId());
607        }
608    }
609
610    @Override
611    public HardwareSpec getHardwareSpec() {
612        return new HardwareSpec() {
613            @Override
614            public boolean isFrontCameraSupported() {
615                return true;
616            }
617
618            @Override
619            public boolean isHdrSupported() {
620                // TODO: Check if the device has HDR and not HDR+.
621                return false;
622            }
623
624            @Override
625            public boolean isHdrPlusSupported() {
626                return GcamHelper.hasGcamCapture();
627            }
628
629            @Override
630            public boolean isFlashSupported() {
631                return true;
632            }
633        };
634    }
635
636    @Override
637    public BottomBarUISpec getBottomBarSpec() {
638        CameraAppUI.BottomBarUISpec bottomBarSpec = new CameraAppUI.BottomBarUISpec();
639        bottomBarSpec.enableGridLines = true;
640        bottomBarSpec.enableCamera = true;
641        bottomBarSpec.cameraCallback = getCameraCallback();
642        bottomBarSpec.enableHdr = GcamHelper.hasGcamCapture();
643        bottomBarSpec.hdrCallback = getHdrButtonCallback();
644        bottomBarSpec.enableSelfTimer = true;
645        bottomBarSpec.showSelfTimer = true;
646        if (!mHdrEnabled) {
647            bottomBarSpec.enableFlash = true;
648        }
649        // Added to handle case of CaptureModule being used only for Gcam.
650        if (mStickyGcamCamera) {
651            bottomBarSpec.enableFlash = false;
652        }
653        return bottomBarSpec;
654    }
655
656    @Override
657    public boolean isUsingBottomBar() {
658        return true;
659    }
660
661    @Override
662    public boolean onKeyDown(int keyCode, KeyEvent event) {
663        switch (keyCode) {
664            case KeyEvent.KEYCODE_CAMERA:
665            case KeyEvent.KEYCODE_DPAD_CENTER:
666                if (mUI.isCountingDown()) {
667                    cancelCountDown();
668                } else if (event.getRepeatCount() == 0) {
669                    onShutterButtonClick();
670                }
671                return true;
672            case KeyEvent.KEYCODE_VOLUME_UP:
673            case KeyEvent.KEYCODE_VOLUME_DOWN:
674                // Prevent default.
675                return true;
676        }
677        return false;
678    }
679
680    @Override
681    public boolean onKeyUp(int keyCode, KeyEvent event) {
682        switch (keyCode) {
683            case KeyEvent.KEYCODE_VOLUME_UP:
684            case KeyEvent.KEYCODE_VOLUME_DOWN:
685                onShutterButtonClick();
686                return true;
687        }
688        return false;
689    }
690
691    /**
692     * Focus sequence starts for zone around tap location for single tap.
693     */
694    @Override
695    public void onSingleTapUp(View view, int x, int y) {
696        Log.v(TAG, "onSingleTapUp x=" + x + " y=" + y);
697        // TODO: This should query actual capability.
698        if (mCameraFacing == Facing.FRONT) {
699            return;
700        }
701        triggerFocusAtScreenCoord(x, y);
702    }
703
704    // TODO: Consider refactoring FocusOverlayManager.
705    // Currently AF state transitions are controlled in OneCameraImpl.
706    // PhotoModule uses FocusOverlayManager which uses API1/portability
707    // logic and coordinates.
708    private void triggerFocusAtScreenCoord(int x, int y) {
709        if (mCamera == null) {
710            // If we receive this after the camera is closed, do nothing.
711            return;
712        }
713
714        mTapToFocusWaitForActiveScan = true;
715        // Show UI immediately even though scan has not started yet.
716        float minEdge = Math.min(mPreviewArea.width(), mPreviewArea.height());
717        mUI.setAutoFocusTarget(x, y, false,
718                (int) (Settings3A.getAutoFocusRegionWidth() * mZoomValue * minEdge),
719                (int) (Settings3A.getMeteringRegionWidth() * mZoomValue * minEdge));
720        mUI.showAutoFocusInProgress();
721
722        // Cancel any scheduled auto focus target UI actions.
723        mMainHandler.removeCallbacks(mHideAutoFocusTargetRunnable);
724        // Timeout in case camera fails to stop (unlikely).
725        mMainHandler.postDelayed(new Runnable() {
726            @Override
727            public void run() {
728                mMainHandler.post(mHideAutoFocusTargetRunnable);
729            }
730        }, FOCUS_UI_TIMEOUT_MILLIS);
731
732        // Normalize coordinates to [0,1] per CameraOne API.
733        float points[] = new float[2];
734        points[0] = (x - mPreviewArea.left) / mPreviewArea.width();
735        points[1] = (y - mPreviewArea.top) / mPreviewArea.height();
736
737        // Rotate coordinates to portrait orientation per CameraOne API.
738        Matrix rotationMatrix = new Matrix();
739        rotationMatrix.setRotate(mDisplayRotation, 0.5f, 0.5f);
740        rotationMatrix.mapPoints(points);
741        mCamera.triggerFocusAndMeterAtPoint(points[0], points[1]);
742
743        // Log touch (screen coordinates).
744        if (mZoomValue == 1f) {
745            TouchCoordinate touchCoordinate = new TouchCoordinate(x - mPreviewArea.left,
746                    y - mPreviewArea.top, mPreviewArea.width(), mPreviewArea.height());
747            // TODO: Add to logging: duration, rotation.
748            UsageStatistics.instance().tapToFocus(touchCoordinate, null);
749        }
750    }
751
752    /**
753     * Show AF target in center of preview.
754     */
755    private void setAutoFocusTargetPassive() {
756        float minEdge = Math.min(mPreviewArea.width(), mPreviewArea.height());
757        mUI.setAutoFocusTarget((int) mPreviewArea.centerX(), (int) mPreviewArea.centerY(),
758                true,
759                (int) (Settings3A.getAutoFocusRegionWidth() * mZoomValue * minEdge),
760                (int) (Settings3A.getMeteringRegionWidth() * mZoomValue * minEdge));
761        mUI.showAutoFocusInProgress();
762    }
763
764    /**
765     * Update UI based on AF state changes.
766     */
767    @Override
768    public void onFocusStatusUpdate(final AutoFocusState state, long frameNumber) {
769        Log.v(TAG, "AF status is state:" + state);
770
771        switch (state) {
772            case PASSIVE_SCAN:
773                mMainHandler.removeCallbacks(mHideAutoFocusTargetRunnable);
774                mMainHandler.post(new Runnable() {
775                    @Override
776                    public void run() {
777                        setAutoFocusTargetPassive();
778                    }
779                });
780                break;
781            case ACTIVE_SCAN:
782                mTapToFocusWaitForActiveScan = false;
783                break;
784            case PASSIVE_FOCUSED:
785            case PASSIVE_UNFOCUSED:
786                mMainHandler.post(new Runnable() {
787                    @Override
788                    public void run() {
789                        mUI.setPassiveFocusSuccess(state == AutoFocusState.PASSIVE_FOCUSED);
790                    }
791                });
792                break;
793            case ACTIVE_FOCUSED:
794            case ACTIVE_UNFOCUSED:
795                if (!mTapToFocusWaitForActiveScan) {
796                    mFocusedAtEnd = state != AutoFocusState.ACTIVE_UNFOCUSED;
797                    mMainHandler.removeCallbacks(mHideAutoFocusTargetRunnable);
798                    mMainHandler.post(mHideAutoFocusTargetRunnable);
799                }
800                break;
801        }
802
803        if (CAPTURE_DEBUG_UI) {
804            measureAutoFocusScans(state, frameNumber);
805        }
806    }
807
808    private void measureAutoFocusScans(final AutoFocusState state, long frameNumber) {
809        // Log AF scan lengths.
810        boolean passive = false;
811        switch (state) {
812            case PASSIVE_SCAN:
813            case ACTIVE_SCAN:
814                if (mAutoFocusScanStartFrame == -1) {
815                    mAutoFocusScanStartFrame = frameNumber;
816                    mAutoFocusScanStartTime = SystemClock.uptimeMillis();
817                }
818                break;
819            case PASSIVE_FOCUSED:
820            case PASSIVE_UNFOCUSED:
821                passive = true;
822            case ACTIVE_FOCUSED:
823            case ACTIVE_UNFOCUSED:
824                if (mAutoFocusScanStartFrame != -1) {
825                    long frames = frameNumber - mAutoFocusScanStartFrame;
826                    long dt = SystemClock.uptimeMillis() - mAutoFocusScanStartTime;
827                    int fps = Math.round(frames * 1000f / dt);
828                    String report = String.format("%s scan: fps=%d frames=%d",
829                            passive ? "CAF" : "AF", fps, frames);
830                    Log.v(TAG, report);
831                    mUI.showDebugMessage(String.format("%d / %d", frames, fps));
832                    mAutoFocusScanStartFrame = -1;
833                }
834                break;
835        }
836    }
837
838    @Override
839    public void onReadyStateChanged(boolean readyForCapture) {
840        if (readyForCapture) {
841            mAppController.getCameraAppUI().enableModeOptions();
842        }
843        mAppController.setShutterEnabled(readyForCapture);
844    }
845
846    @Override
847    public String getPeekAccessibilityString() {
848        return mAppController.getAndroidContext()
849                .getResources().getString(R.string.photo_accessibility_peek);
850    }
851
852    @Override
853    public void onThumbnailResult(Bitmap bitmap) {
854        // TODO
855    }
856
857    @Override
858    public void onPictureTaken(CaptureSession session) {
859        mAppController.getCameraAppUI().enableModeOptions();
860    }
861
862    @Override
863    public void onPictureSaved(Uri uri) {
864        mAppController.notifyNewMedia(uri);
865    }
866
867    @Override
868    public void onTakePictureProgress(float progress) {
869        mUI.setPictureTakingProgress((int) (progress * 100));
870    }
871
872    @Override
873    public void onPictureTakenFailed() {
874    }
875
876    @Override
877    public void onSettingChanged(SettingsManager settingsManager, String key) {
878        // TODO Auto-generated method stub
879    }
880
881    /**
882     * Updates the preview transform matrix to adapt to the current preview
883     * width, height, and orientation.
884     */
885    public void updatePreviewTransform() {
886        int width;
887        int height;
888        synchronized (mDimensionLock) {
889            width = mScreenWidth;
890            height = mScreenHeight;
891        }
892        updatePreviewTransform(width, height);
893    }
894
895    /**
896     * Set zoom value.
897     *
898     * @param zoom Zoom value, must be between 1.0 and mCamera.getMaxZoom().
899     */
900    public void setZoom(float zoom) {
901        mZoomValue = zoom;
902        if (mCamera != null) {
903            mCamera.setZoom(zoom);
904        }
905    }
906
907    /**
908     * TODO: Remove this method once we are in pure CaptureModule land.
909     */
910    private String getBackFacingCameraId() {
911        if (!(mCameraManager instanceof OneCameraManagerImpl)) {
912            throw new IllegalStateException("This should never be called with Camera API V1");
913        }
914        OneCameraManagerImpl manager = (OneCameraManagerImpl) mCameraManager;
915        return manager.getFirstBackCameraId();
916    }
917
918    /**
919     * @return Depending on whether we're in sticky-HDR mode or not, return the
920     *         proper callback to be used for when the HDR/HDR+ button is
921     *         pressed.
922     */
923    private ButtonManager.ButtonCallback getHdrButtonCallback() {
924        if (mStickyGcamCamera) {
925            return new ButtonManager.ButtonCallback() {
926                @Override
927                public void onStateChanged(int state) {
928                    if (mPaused) {
929                        return;
930                    }
931                    if (state == ButtonManager.ON) {
932                        throw new IllegalStateException(
933                                "Can't leave hdr plus mode if switching to hdr plus mode.");
934                    }
935                    SettingsManager settingsManager = mAppController.getSettingsManager();
936                    settingsManager.set(mAppController.getModuleScope(),
937                            Keys.KEY_REQUEST_RETURN_HDR_PLUS, false);
938                    switchToRegularCapture();
939                }
940            };
941        } else {
942            return new ButtonManager.ButtonCallback() {
943                @Override
944                public void onStateChanged(int hdrEnabled) {
945                    if (mPaused) {
946                        return;
947                    }
948                    Log.d(TAG, "HDR enabled =" + hdrEnabled);
949                    mHdrEnabled = hdrEnabled == 1;
950                    switchCamera();
951                }
952            };
953        }
954    }
955
956    /**
957     * @return Depending on whether we're in sticky-HDR mode or not, this
958     *         returns the proper callback to be used for when the camera
959     *         (front/back switch) button is pressed.
960     */
961    private ButtonManager.ButtonCallback getCameraCallback() {
962        if (mStickyGcamCamera) {
963            return new ButtonManager.ButtonCallback() {
964                @Override
965                public void onStateChanged(int state) {
966                    if (mPaused) {
967                        return;
968                    }
969
970                    // At the time this callback is fired, the camera id setting
971                    // has changed to the desired camera.
972                    SettingsManager settingsManager = mAppController.getSettingsManager();
973                    if (Keys.isCameraBackFacing(settingsManager,
974                            mAppController.getModuleScope())) {
975                        throw new IllegalStateException(
976                                "Hdr plus should never be switching from front facing camera.");
977                    }
978
979                    // Switch to photo mode, but request a return to hdr plus on
980                    // switching to back camera again.
981                    settingsManager.set(mAppController.getModuleScope(),
982                            Keys.KEY_REQUEST_RETURN_HDR_PLUS, true);
983                    switchToRegularCapture();
984                }
985            };
986        } else {
987            return new ButtonManager.ButtonCallback() {
988                @Override
989                public void onStateChanged(int cameraId) {
990                    if (mPaused) {
991                        return;
992                    }
993
994                    // At the time this callback is fired, the camera id
995                    // has be set to the desired camera.
996                    mSettingsManager.set(mAppController.getModuleScope(), Keys.KEY_CAMERA_ID,
997                            cameraId);
998
999                    Log.d(TAG, "Start to switch camera. cameraId=" + cameraId);
1000                    mCameraFacing = getFacingFromCameraId(cameraId);
1001                    switchCamera();
1002                }
1003            };
1004        }
1005    }
1006
1007    /**
1008     * Switches to PhotoModule to do regular photo captures.
1009     * <p>
1010     * TODO: Remove this once we use CaptureModule for photo taking.
1011     */
1012    private void switchToRegularCapture() {
1013        // Turn off HDR+ before switching back to normal photo mode.
1014        SettingsManager settingsManager = mAppController.getSettingsManager();
1015        settingsManager.set(SettingsManager.SCOPE_GLOBAL, Keys.KEY_CAMERA_HDR_PLUS, false);
1016
1017        // Disable this button to prevent callbacks from this module from firing
1018        // while we are transitioning modules.
1019        ButtonManager buttonManager = mAppController.getButtonManager();
1020        buttonManager.disableButtonClick(ButtonManager.BUTTON_HDR_PLUS);
1021        mAppController.getCameraAppUI().freezeScreenUntilPreviewReady();
1022        mAppController.onModeSelected(mContext.getResources().getInteger(
1023                R.integer.camera_mode_photo));
1024        buttonManager.enableButtonClick(ButtonManager.BUTTON_HDR_PLUS);
1025    }
1026
1027    /**
1028     * Called when the preview started. Informs the app controller and queues a
1029     * transform update when the next preview frame arrives.
1030     */
1031    private void onPreviewStarted() {
1032        if (mState == ModuleState.WATCH_FOR_NEXT_FRAME_AFTER_PREVIEW_STARTED) {
1033            mState = ModuleState.UPDATE_TRANSFORM_ON_NEXT_SURFACE_TEXTURE_UPDATE;
1034        }
1035        mAppController.onPreviewStarted();
1036    }
1037
1038    /**
1039     * Update the preview transform based on the new dimensions. Will not force
1040     * an update, if it's not necessary.
1041     */
1042    private void updatePreviewTransform(int incomingWidth, int incomingHeight) {
1043        updatePreviewTransform(incomingWidth, incomingHeight, false);
1044    }
1045
1046    /***
1047     * Update the preview transform based on the new dimensions. TODO: Make work
1048     * with all: aspect ratios/resolutions x screens/cameras.
1049     */
1050    private void updatePreviewTransform(int incomingWidth, int incomingHeight,
1051            boolean forceUpdate) {
1052        Log.d(TAG, "updatePreviewTransform: " + incomingWidth + " x " + incomingHeight);
1053
1054        synchronized (mDimensionLock) {
1055            int incomingRotation = CameraUtil
1056                    .getDisplayRotation(mContext);
1057            // Check for an actual change:
1058            if (mScreenHeight == incomingHeight && mScreenWidth == incomingWidth &&
1059                    incomingRotation == mDisplayRotation && !forceUpdate) {
1060                return;
1061            }
1062            // Update display rotation and dimensions
1063            mDisplayRotation = incomingRotation;
1064            mScreenWidth = incomingWidth;
1065            mScreenHeight = incomingHeight;
1066            updatePreviewBufferDimension();
1067
1068            mPreviewTranformationMatrix = mAppController.getCameraAppUI().getPreviewTransform(
1069                    mPreviewTranformationMatrix);
1070            int width = mScreenWidth;
1071            int height = mScreenHeight;
1072
1073            // Assumptions:
1074            // - Aspect ratio for the sensor buffers is in landscape
1075            // orientation,
1076            // - Dimensions of buffers received are rotated to the natural
1077            // device orientation.
1078            // - The contents of each buffer are rotated by the inverse of
1079            // the display rotation.
1080            // - Surface scales the buffer to fit the current view bounds.
1081
1082            // Get natural orientation and buffer dimensions
1083            int naturalOrientation = CaptureModuleUtil
1084                    .getDeviceNaturalOrientation(mContext);
1085            int effectiveWidth = mPreviewBufferWidth;
1086            int effectiveHeight = mPreviewBufferHeight;
1087
1088            if (DEBUG) {
1089                Log.v(TAG, "Rotation: " + mDisplayRotation);
1090                Log.v(TAG, "Screen Width: " + mScreenWidth);
1091                Log.v(TAG, "Screen Height: " + mScreenHeight);
1092                Log.v(TAG, "Buffer width: " + mPreviewBufferWidth);
1093                Log.v(TAG, "Buffer height: " + mPreviewBufferHeight);
1094                Log.v(TAG, "Natural orientation: " + naturalOrientation);
1095            }
1096
1097            // If natural orientation is portrait, rotate the buffer
1098            // dimensions
1099            if (naturalOrientation == Configuration.ORIENTATION_PORTRAIT) {
1100                int temp = effectiveWidth;
1101                effectiveWidth = effectiveHeight;
1102                effectiveHeight = temp;
1103            }
1104
1105            // Find and center view rect and buffer rect
1106            RectF viewRect = new RectF(0, 0, width, height);
1107            RectF bufRect = new RectF(0, 0, effectiveWidth, effectiveHeight);
1108            float centerX = viewRect.centerX();
1109            float centerY = viewRect.centerY();
1110            bufRect.offset(centerX - bufRect.centerX(), centerY - bufRect.centerY());
1111
1112            // Undo ScaleToFit.FILL done by the surface
1113            mPreviewTranformationMatrix.setRectToRect(viewRect, bufRect, Matrix.ScaleToFit.FILL);
1114
1115            // Rotate buffer contents to proper orientation
1116            mPreviewTranformationMatrix.postRotate(getPreviewOrientation(mDisplayRotation),
1117                    centerX, centerY);
1118
1119            // TODO: This is probably only working for the N5. Need to test
1120            // on a device like N10 with different sensor orientation.
1121            if ((mDisplayRotation % 180) == 90) {
1122                int temp = effectiveWidth;
1123                effectiveWidth = effectiveHeight;
1124                effectiveHeight = temp;
1125            }
1126
1127            // Scale to fit view, cropping the longest dimension
1128            float scale =
1129                    Math.min(width / (float) effectiveWidth, height
1130                            / (float) effectiveHeight);
1131            mPreviewTranformationMatrix.postScale(scale, scale, centerX, centerY);
1132
1133            // TODO: Take these quantities from mPreviewArea.
1134            float previewWidth = effectiveWidth * scale;
1135            float previewHeight = effectiveHeight * scale;
1136            float previewCenterX = previewWidth / 2;
1137            float previewCenterY = previewHeight / 2;
1138            mPreviewTranformationMatrix.postTranslate(previewCenterX - centerX, previewCenterY
1139                    - centerY);
1140
1141            mAppController.updatePreviewTransform(mPreviewTranformationMatrix);
1142            mAppController.getCameraAppUI().hideLetterboxing();
1143            // if (mGcamProxy != null) {
1144            // mGcamProxy.postSetAspectRatio(mFinalAspectRatio);
1145            // }
1146            // mUI.updatePreviewAreaRect(new RectF(0, 0, previewWidth,
1147            // previewHeight));
1148
1149            // TODO: Add face detection.
1150            // Characteristics info =
1151            // mapp.getCameraProvider().getCharacteristics(0);
1152            // mUI.setupFaceDetection(CameraUtil.getDisplayOrientation(incomingRotation,
1153            // info), false);
1154            // updateCamera2FaceBoundTransform(new
1155            // RectF(mEffectiveCropRegion),
1156            // new RectF(0, 0, mBufferWidth, mBufferHeight),
1157            // new RectF(0, 0, previewWidth, previewHeight), getRotation());
1158        }
1159    }
1160
1161    /**
1162     * Based on the current picture size, selects the best preview dimension and
1163     * stores it in {@link #mPreviewBufferWidth} and
1164     * {@link #mPreviewBufferHeight}.
1165     */
1166    private void updatePreviewBufferDimension() {
1167        if (mCamera == null) {
1168            return;
1169        }
1170
1171        Size pictureSize = getPictureSizeFromSettings();
1172        Size previewBufferSize = mCamera.pickPreviewSize(pictureSize, mContext);
1173        mPreviewBufferWidth = previewBufferSize.getWidth();
1174        mPreviewBufferHeight = previewBufferSize.getHeight();
1175    }
1176
1177    /**
1178     * Resets the default buffer size to the initially calculated size.
1179     */
1180    private void resetDefaultBufferSize() {
1181        synchronized (mSurfaceLock) {
1182            if (mPreviewTexture != null) {
1183                mPreviewTexture.setDefaultBufferSize(mPreviewBufferWidth, mPreviewBufferHeight);
1184            }
1185        }
1186    }
1187
1188    /**
1189     * Open camera and start the preview.
1190     */
1191    private void openCameraAndStartPreview() {
1192        // Only enable HDR on the back camera
1193        boolean useHdr = mHdrEnabled && mCameraFacing == Facing.BACK;
1194
1195        try {
1196            // TODO Given the current design, we cannot guarantee that one of
1197            // CaptureReadyCallback.onSetupFailed or onReadyForCapture will
1198            // be called (see below), so it's possible that
1199            // mCameraOpenCloseLock.release() is never called under extremely
1200            // rare cases.  If we leak the lock, this timeout ensures that we at
1201            // least crash so we don't deadlock the app.
1202            if (!mCameraOpenCloseLock.tryAcquire(CAMERA_OPEN_CLOSE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
1203                throw new RuntimeException("Time out waiting to acquire camera-open lock.");
1204            }
1205        } catch (InterruptedException e) {
1206            throw new RuntimeException("Interrupted while waiting to acquire camera-open lock.", e);
1207        }
1208        mCameraManager.open(mCameraFacing, useHdr, getPictureSizeFromSettings(),
1209                new OpenCallback() {
1210                    @Override
1211                    public void onFailure() {
1212                        Log.e(TAG, "Could not open camera.");
1213                        mCamera = null;
1214                        mCameraOpenCloseLock.release();
1215                        mAppController.showErrorAndFinish(R.string.cannot_connect_camera);
1216                    }
1217
1218                    @Override
1219                    public void onCameraClosed() {
1220                        mCamera = null;
1221                        mCameraOpenCloseLock.release();
1222                    }
1223
1224                    @Override
1225                    public void onCameraOpened(final OneCamera camera) {
1226                        Log.d(TAG, "onCameraOpened: " + camera);
1227                        mCamera = camera;
1228                        updatePreviewBufferDimension();
1229
1230                        // If the surface texture is not destroyed, it may have
1231                        // the last frame lingering. We need to hold off setting
1232                        // transform until preview is started.
1233                        resetDefaultBufferSize();
1234                        mState = ModuleState.WATCH_FOR_NEXT_FRAME_AFTER_PREVIEW_STARTED;
1235                        Log.d(TAG, "starting preview ...");
1236
1237                        // TODO: Consider rolling these two calls into one.
1238                        camera.startPreview(new Surface(mPreviewTexture),
1239                                new CaptureReadyCallback() {
1240                                    @Override
1241                                    public void onSetupFailed() {
1242                                        // We must release this lock here, before posting
1243                                        // to the main handler since we may be blocked
1244                                        // in pause(), getting ready to close the camera.
1245                                        mCameraOpenCloseLock.release();
1246                                        Log.e(TAG, "Could not set up preview.");
1247                                        mMainHandler.post(new Runnable() {
1248                                           @Override
1249                                           public void run() {
1250                                               if (mCamera == null) {
1251                                                   Log.d(TAG, "Camera closed, aborting.");
1252                                                   return;
1253                                               }
1254                                               mCamera.close(null);
1255                                               mCamera = null;
1256                                               // TODO: Show an error message and exit.
1257                                           }
1258                                        });
1259                                    }
1260
1261                                    @Override
1262                                    public void onReadyForCapture() {
1263                                        // We must release this lock here, before posting
1264                                        // to the main handler since we may be blocked
1265                                        // in pause(), getting ready to close the camera.
1266                                        mCameraOpenCloseLock.release();
1267                                        mMainHandler.post(new Runnable() {
1268                                           @Override
1269                                           public void run() {
1270                                               Log.d(TAG, "Ready for capture.");
1271                                               if (mCamera == null) {
1272                                                   Log.d(TAG, "Camera closed, aborting.");
1273                                                   return;
1274                                               }
1275                                               onPreviewStarted();
1276                                               // Enable zooming after preview has
1277                                               // started.
1278                                               mUI.initializeZoom(mCamera.getMaxZoom());
1279                                               mCamera.setFocusStateListener(CaptureModule.this);
1280                                               mCamera.setReadyStateChangedListener(CaptureModule.this);
1281                                           }
1282                                        });
1283                                    }
1284                                });
1285                    }
1286                }, mCameraHandler);
1287    }
1288
1289    private void closeCamera() {
1290        try {
1291            mCameraOpenCloseLock.acquire();
1292        } catch(InterruptedException e) {
1293            throw new RuntimeException("Interrupted while waiting to acquire camera-open lock.", e);
1294        }
1295        try {
1296            if (mCamera != null) {
1297                mCamera.setFocusStateListener(null);
1298                mCamera.close(null);
1299                mCamera = null;
1300            }
1301        } finally {
1302            mCameraOpenCloseLock.release();
1303        }
1304    }
1305
1306    private int getOrientation() {
1307        if (mAppController.isAutoRotateScreen()) {
1308            return mDisplayRotation;
1309        } else {
1310            return mOrientation;
1311        }
1312    }
1313
1314    /**
1315     * @return Whether we are resuming from within the lockscreen.
1316     */
1317    private static boolean isResumeFromLockscreen(Activity activity) {
1318        String action = activity.getIntent().getAction();
1319        return (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(action)
1320        || MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action));
1321    }
1322
1323    /**
1324     * Re-initialize the camera if e.g. the HDR mode or facing property changed.
1325     */
1326    private void switchCamera() {
1327        if (mPaused) {
1328            return;
1329        }
1330        cancelCountDown();
1331        mAppController.freezeScreenUntilPreviewReady();
1332        initSurface(mPreviewTexture);
1333
1334        // TODO: Un-comment once we have focus back.
1335        // if (mFocusManager != null) {
1336        // mFocusManager.removeMessages();
1337        // }
1338        // mFocusManager.setMirror(mMirror);
1339    }
1340
1341    private Size getPictureSizeFromSettings() {
1342        String pictureSizeKey = mCameraFacing == Facing.FRONT ? Keys.KEY_PICTURE_SIZE_FRONT
1343                : Keys.KEY_PICTURE_SIZE_BACK;
1344        return mSettingsManager.getSize(SettingsManager.SCOPE_GLOBAL, pictureSizeKey);
1345    }
1346
1347    private int getPreviewOrientation(int deviceOrientationDegrees) {
1348        // Important: Camera2 buffers are already rotated to the natural
1349        // orientation of the device (at least for the back-camera).
1350
1351        // TODO: Remove this hack for the front camera as soon as b/16637957 is
1352        // fixed.
1353        if (mCameraFacing == Facing.FRONT) {
1354            deviceOrientationDegrees += 180;
1355        }
1356        return (360 - deviceOrientationDegrees) % 360;
1357    }
1358
1359    /**
1360     * Returns which way around the camera is facing, based on it's ID.
1361     * <p>
1362     * TODO: This needs to change so that we store the direction directly in the
1363     * settings, rather than a Camera ID.
1364     */
1365    private static Facing getFacingFromCameraId(int cameraId) {
1366        return cameraId == 1 ? Facing.FRONT : Facing.BACK;
1367    }
1368
1369    private void resetTextureBufferSize() {
1370        // Reset the default buffer sizes on the shared SurfaceTexture
1371        // so they are not scaled for gcam.
1372        //
1373        // According to the documentation for
1374        // SurfaceTexture.setDefaultBufferSize,
1375        // photo and video based image producers (presumably only Camera 1 api),
1376        // override this buffer size. Any module that uses egl to render to a
1377        // SurfaceTexture must have these buffer sizes reset manually. Otherwise
1378        // the SurfaceTexture cannot be transformed by matrix set on the
1379        // TextureView.
1380        if (mPreviewTexture != null) {
1381            mPreviewTexture.setDefaultBufferSize(mAppController.getCameraAppUI().getSurfaceWidth(),
1382                    mAppController.getCameraAppUI().getSurfaceHeight());
1383        }
1384    }
1385
1386    /**
1387     * @return The currently set Flash settings. Defaults to AUTO if the setting
1388     *         could not be parsed.
1389     */
1390    private Flash getFlashModeFromSettings() {
1391        String flashSetting = mSettingsManager.getString(mAppController.getCameraScope(),
1392                Keys.KEY_FLASH_MODE);
1393        try {
1394            return Flash.valueOf(flashSetting.toUpperCase());
1395        } catch (IllegalArgumentException ex) {
1396            Log.w(TAG, "Could not parse Flash Setting. Defaulting to AUTO.");
1397            return Flash.AUTO;
1398        }
1399    }
1400}
1401