Home | History | Annotate | Download | only in camera
      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 
     17 package com.android.camera;
     18 
     19 import android.app.Activity;
     20 import android.content.ActivityNotFoundException;
     21 import android.content.BroadcastReceiver;
     22 import android.content.ContentResolver;
     23 import android.content.ContentValues;
     24 import android.content.Context;
     25 import android.content.Intent;
     26 import android.content.IntentFilter;
     27 import android.graphics.Bitmap;
     28 import android.graphics.Point;
     29 import android.graphics.SurfaceTexture;
     30 import android.hardware.Camera;
     31 import android.location.Location;
     32 import android.media.AudioManager;
     33 import android.media.CamcorderProfile;
     34 import android.media.CameraProfile;
     35 import android.media.MediaRecorder;
     36 import android.net.Uri;
     37 import android.os.Build;
     38 import android.os.Bundle;
     39 import android.os.Handler;
     40 import android.os.Looper;
     41 import android.os.Message;
     42 import android.os.ParcelFileDescriptor;
     43 import android.os.SystemClock;
     44 import android.provider.MediaStore;
     45 import android.provider.MediaStore.MediaColumns;
     46 import android.provider.MediaStore.Video;
     47 import android.view.KeyEvent;
     48 import android.view.View;
     49 import android.widget.Toast;
     50 
     51 import com.android.camera.app.AppController;
     52 import com.android.camera.app.CameraAppUI;
     53 import com.android.camera.app.LocationManager;
     54 import com.android.camera.app.MediaSaver;
     55 import com.android.camera.app.MemoryManager;
     56 import com.android.camera.app.MemoryManager.MemoryListener;
     57 import com.android.camera.app.OrientationManager;
     58 import com.android.camera.debug.Log;
     59 import com.android.camera.exif.ExifInterface;
     60 import com.android.camera.hardware.HardwareSpec;
     61 import com.android.camera.hardware.HardwareSpecImpl;
     62 import com.android.camera.module.ModuleController;
     63 import com.android.camera.settings.Keys;
     64 import com.android.camera.settings.SettingsManager;
     65 import com.android.camera.settings.SettingsUtil;
     66 import com.android.camera.ui.TouchCoordinate;
     67 import com.android.camera.util.AndroidServices;
     68 import com.android.camera.util.ApiHelper;
     69 import com.android.camera.util.CameraUtil;
     70 import com.android.camera.stats.UsageStatistics;
     71 import com.android.camera.util.Size;
     72 import com.android.camera2.R;
     73 import com.android.ex.camera2.portability.CameraAgent;
     74 import com.android.ex.camera2.portability.CameraAgent.CameraPictureCallback;
     75 import com.android.ex.camera2.portability.CameraAgent.CameraProxy;
     76 import com.android.ex.camera2.portability.CameraCapabilities;
     77 import com.android.ex.camera2.portability.CameraDeviceInfo.Characteristics;
     78 import com.android.ex.camera2.portability.CameraSettings;
     79 import com.google.common.logging.eventprotos;
     80 
     81 import java.io.File;
     82 import java.io.IOException;
     83 import java.text.SimpleDateFormat;
     84 import java.util.ArrayList;
     85 import java.util.Date;
     86 import java.util.Iterator;
     87 import java.util.List;
     88 import java.util.Set;
     89 
     90 public class VideoModule extends CameraModule
     91         implements FocusOverlayManager.Listener, MediaRecorder.OnErrorListener,
     92         MediaRecorder.OnInfoListener, MemoryListener,
     93         OrientationManager.OnOrientationChangeListener, VideoController {
     94 
     95     private static final Log.Tag TAG = new Log.Tag("VideoModule");
     96 
     97     // Messages defined for the UI thread handler.
     98     private static final int MSG_CHECK_DISPLAY_ROTATION = 4;
     99     private static final int MSG_UPDATE_RECORD_TIME = 5;
    100     private static final int MSG_ENABLE_SHUTTER_BUTTON = 6;
    101     private static final int MSG_SWITCH_CAMERA = 8;
    102     private static final int MSG_SWITCH_CAMERA_START_ANIMATION = 9;
    103 
    104     private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms
    105 
    106     /**
    107      * An unpublished intent flag requesting to start recording straight away
    108      * and return as soon as recording is stopped.
    109      * TODO: consider publishing by moving into MediaStore.
    110      */
    111     private static final String EXTRA_QUICK_CAPTURE =
    112             "android.intent.extra.quickCapture";
    113 
    114     // module fields
    115     private CameraActivity mActivity;
    116     private boolean mPaused;
    117 
    118     // if, during and intent capture, the activity is paused (e.g. when app switching or reviewing a
    119     // shot video), we don't want the bottom bar intent ui to reset to the capture button
    120     private boolean mDontResetIntentUiOnResume;
    121 
    122     private int mCameraId;
    123     private CameraSettings mCameraSettings;
    124     private CameraCapabilities mCameraCapabilities;
    125     private HardwareSpec mHardwareSpec;
    126 
    127     private boolean mIsInReviewMode;
    128     private boolean mSnapshotInProgress = false;
    129 
    130     // Preference must be read before starting preview. We check this before starting
    131     // preview.
    132     private boolean mPreferenceRead;
    133 
    134     private boolean mIsVideoCaptureIntent;
    135     private boolean mQuickCapture;
    136 
    137     private MediaRecorder mMediaRecorder;
    138     /** Manager used to mute sounds and vibrations during video recording. */
    139     private AudioManager mAudioManager;
    140     /*
    141      * The ringer mode that was set when video recording started. We use this to
    142      * reset the mode once video recording has stopped.
    143      */
    144     private int mOriginalRingerMode;
    145 
    146     private boolean mSwitchingCamera;
    147     private boolean mMediaRecorderRecording = false;
    148     private long mRecordingStartTime;
    149     private boolean mRecordingTimeCountsDown = false;
    150     private long mOnResumeTime;
    151     // The video file that the hardware camera is about to record into
    152     // (or is recording into.
    153     private String mVideoFilename;
    154     private ParcelFileDescriptor mVideoFileDescriptor;
    155 
    156     // The video file that has already been recorded, and that is being
    157     // examined by the user.
    158     private String mCurrentVideoFilename;
    159     private Uri mCurrentVideoUri;
    160     private boolean mCurrentVideoUriFromMediaSaved;
    161     private ContentValues mCurrentVideoValues;
    162 
    163     private CamcorderProfile mProfile;
    164 
    165     // The video duration limit. 0 means no limit.
    166     private int mMaxVideoDurationInMs;
    167 
    168     boolean mPreviewing = false; // True if preview is started.
    169     // The display rotation in degrees. This is only valid when mPreviewing is
    170     // true.
    171     private int mDisplayRotation;
    172     private int mCameraDisplayOrientation;
    173     private AppController mAppController;
    174 
    175     private int mDesiredPreviewWidth;
    176     private int mDesiredPreviewHeight;
    177     private ContentResolver mContentResolver;
    178 
    179     private LocationManager mLocationManager;
    180 
    181     private int mPendingSwitchCameraId;
    182     private final Handler mHandler = new MainHandler();
    183     private VideoUI mUI;
    184     private CameraProxy mCameraDevice;
    185 
    186     private float mZoomValue;  // The current zoom ratio.
    187 
    188     private final MediaSaver.OnMediaSavedListener mOnVideoSavedListener =
    189             new MediaSaver.OnMediaSavedListener() {
    190                 @Override
    191                 public void onMediaSaved(Uri uri) {
    192                     if (uri != null) {
    193                         mCurrentVideoUri = uri;
    194                         mCurrentVideoUriFromMediaSaved = true;
    195                         onVideoSaved();
    196                         mActivity.notifyNewMedia(uri);
    197                     }
    198                 }
    199             };
    200 
    201     private final MediaSaver.OnMediaSavedListener mOnPhotoSavedListener =
    202             new MediaSaver.OnMediaSavedListener() {
    203                 @Override
    204                 public void onMediaSaved(Uri uri) {
    205                     if (uri != null) {
    206                         mActivity.notifyNewMedia(uri);
    207                     }
    208                 }
    209             };
    210     private FocusOverlayManager mFocusManager;
    211     private boolean mMirror;
    212     private boolean mFocusAreaSupported;
    213     private boolean mMeteringAreaSupported;
    214 
    215     private final CameraAgent.CameraAFCallback mAutoFocusCallback =
    216             new CameraAgent.CameraAFCallback() {
    217         @Override
    218         public void onAutoFocus(boolean focused, CameraProxy camera) {
    219             if (mPaused) {
    220                 return;
    221             }
    222             mFocusManager.onAutoFocus(focused, false);
    223         }
    224     };
    225 
    226     private final Object mAutoFocusMoveCallback =
    227             ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
    228                     ? new CameraAgent.CameraAFMoveCallback() {
    229                 @Override
    230                 public void onAutoFocusMoving(boolean moving, CameraProxy camera) {
    231                      mFocusManager.onAutoFocusMoving(moving);
    232                 }
    233             } : null;
    234 
    235     /**
    236      * This Handler is used to post message back onto the main thread of the
    237      * application.
    238      */
    239     private class MainHandler extends Handler {
    240         @Override
    241         public void handleMessage(Message msg) {
    242             switch (msg.what) {
    243 
    244                 case MSG_ENABLE_SHUTTER_BUTTON:
    245                     mAppController.setShutterEnabled(true);
    246                     break;
    247 
    248                 case MSG_UPDATE_RECORD_TIME: {
    249                     updateRecordingTime();
    250                     break;
    251                 }
    252 
    253                 case MSG_CHECK_DISPLAY_ROTATION: {
    254                     // Restart the preview if display rotation has changed.
    255                     // Sometimes this happens when the device is held upside
    256                     // down and camera app is opened. Rotation animation will
    257                     // take some time and the rotation value we have got may be
    258                     // wrong. Framework does not have a callback for this now.
    259                     if ((CameraUtil.getDisplayRotation() != mDisplayRotation)
    260                             && !mMediaRecorderRecording && !mSwitchingCamera) {
    261                         startPreview();
    262                     }
    263                     if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
    264                         mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100);
    265                     }
    266                     break;
    267                 }
    268 
    269                 case MSG_SWITCH_CAMERA: {
    270                     switchCamera();
    271                     break;
    272                 }
    273 
    274                 case MSG_SWITCH_CAMERA_START_ANIMATION: {
    275                     //TODO:
    276                     //((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
    277 
    278                     // Enable all camera controls.
    279                     mSwitchingCamera = false;
    280                     break;
    281                 }
    282 
    283                 default:
    284                     Log.v(TAG, "Unhandled message: " + msg.what);
    285                     break;
    286             }
    287         }
    288     }
    289 
    290     private BroadcastReceiver mReceiver = null;
    291 
    292     private class MyBroadcastReceiver extends BroadcastReceiver {
    293         @Override
    294         public void onReceive(Context context, Intent intent) {
    295             String action = intent.getAction();
    296             if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
    297                 stopVideoRecording();
    298             } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
    299                 Toast.makeText(mActivity,
    300                         mActivity.getResources().getString(R.string.wait), Toast.LENGTH_LONG).show();
    301             }
    302         }
    303     }
    304 
    305     private int mShutterIconId;
    306 
    307 
    308     /**
    309      * Construct a new video module.
    310      */
    311     public VideoModule(AppController app) {
    312         super(app);
    313     }
    314 
    315     @Override
    316     public String getPeekAccessibilityString() {
    317         return mAppController.getAndroidContext()
    318             .getResources().getString(R.string.video_accessibility_peek);
    319     }
    320 
    321     private String createName(long dateTaken) {
    322         Date date = new Date(dateTaken);
    323         SimpleDateFormat dateFormat = new SimpleDateFormat(
    324                 mActivity.getString(R.string.video_file_name_format));
    325 
    326         return dateFormat.format(date);
    327     }
    328 
    329     @Override
    330     public void init(CameraActivity activity, boolean isSecureCamera, boolean isCaptureIntent) {
    331         mActivity = activity;
    332         // TODO: Need to look at the controller interface to see if we can get
    333         // rid of passing in the activity directly.
    334         mAppController = mActivity;
    335         mAudioManager = AndroidServices.instance().provideAudioManager();
    336 
    337         mActivity.updateStorageSpaceAndHint(null);
    338 
    339         mUI = new VideoUI(mActivity, this,  mActivity.getModuleLayoutRoot());
    340         mActivity.setPreviewStatusListener(mUI);
    341 
    342         SettingsManager settingsManager = mActivity.getSettingsManager();
    343         mCameraId = settingsManager.getInteger(mAppController.getModuleScope(),
    344                                                Keys.KEY_CAMERA_ID);
    345 
    346         /*
    347          * To reduce startup time, we start the preview in another thread.
    348          * We make sure the preview is started at the end of onCreate.
    349          */
    350         requestCamera(mCameraId);
    351 
    352         mContentResolver = mActivity.getContentResolver();
    353 
    354         // Surface texture is from camera screen nail and startPreview needs it.
    355         // This must be done before startPreview.
    356         mIsVideoCaptureIntent = isVideoCaptureIntent();
    357 
    358         mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
    359         mLocationManager = mActivity.getLocationManager();
    360 
    361         mUI.setOrientationIndicator(0, false);
    362         setDisplayOrientation();
    363 
    364         mPendingSwitchCameraId = -1;
    365 
    366         mShutterIconId = CameraUtil.getCameraShutterIconId(
    367                 mAppController.getCurrentModuleIndex(), mAppController.getAndroidContext());
    368     }
    369 
    370     @Override
    371     public boolean isUsingBottomBar() {
    372         return true;
    373     }
    374 
    375     private void initializeControlByIntent() {
    376         if (isVideoCaptureIntent()) {
    377             if (!mDontResetIntentUiOnResume) {
    378                 mActivity.getCameraAppUI().transitionToIntentCaptureLayout();
    379             }
    380             // reset the flag
    381             mDontResetIntentUiOnResume = false;
    382         }
    383     }
    384 
    385     @Override
    386     public void onSingleTapUp(View view, int x, int y) {
    387         if (mPaused || mCameraDevice == null) {
    388             return;
    389         }
    390         if (mMediaRecorderRecording) {
    391             if (!mSnapshotInProgress) {
    392                 takeASnapshot();
    393             }
    394             return;
    395         }
    396         // Check if metering area or focus area is supported.
    397         if (!mFocusAreaSupported && !mMeteringAreaSupported) {
    398             return;
    399         }
    400         // Tap to focus.
    401         mFocusManager.onSingleTapUp(x, y);
    402     }
    403 
    404     private void takeASnapshot() {
    405         // Only take snapshots if video snapshot is supported by device
    406         if(!mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT)) {
    407             Log.w(TAG, "Cannot take a video snapshot - not supported by hardware");
    408             return;
    409         }
    410         if (!mIsVideoCaptureIntent) {
    411             if (!mMediaRecorderRecording || mPaused || mSnapshotInProgress
    412                     || !mAppController.isShutterEnabled() || mCameraDevice == null) {
    413                 return;
    414             }
    415 
    416             Location loc = mLocationManager.getCurrentLocation();
    417             CameraUtil.setGpsParameters(mCameraSettings, loc);
    418             mCameraDevice.applySettings(mCameraSettings);
    419 
    420             Log.i(TAG, "Video snapshot start");
    421             mCameraDevice.takePicture(mHandler,
    422                     null, null, null, new JpegPictureCallback(loc));
    423             showVideoSnapshotUI(true);
    424             mSnapshotInProgress = true;
    425         }
    426     }
    427 
    428      private void updateAutoFocusMoveCallback() {
    429         if (mPaused || mCameraDevice == null) {
    430             return;
    431         }
    432 
    433         if (mCameraSettings.getCurrentFocusMode() == CameraCapabilities.FocusMode.CONTINUOUS_PICTURE) {
    434             mCameraDevice.setAutoFocusMoveCallback(mHandler,
    435                     (CameraAgent.CameraAFMoveCallback) mAutoFocusMoveCallback);
    436         } else {
    437             mCameraDevice.setAutoFocusMoveCallback(null, null);
    438         }
    439     }
    440 
    441     /**
    442      * @return Whether the currently active camera is front-facing.
    443      */
    444     private boolean isCameraFrontFacing() {
    445         return mAppController.getCameraProvider().getCharacteristics(mCameraId)
    446                 .isFacingFront();
    447     }
    448 
    449     /**
    450      * @return Whether the currently active camera is back-facing.
    451      */
    452     private boolean isCameraBackFacing() {
    453         return mAppController.getCameraProvider().getCharacteristics(mCameraId)
    454                 .isFacingBack();
    455     }
    456 
    457     /**
    458      * The focus manager gets initialized after camera is available.
    459      */
    460     private void initializeFocusManager() {
    461         // Create FocusManager object. startPreview needs it.
    462         // if mFocusManager not null, reuse it
    463         // otherwise create a new instance
    464         if (mFocusManager != null) {
    465             mFocusManager.removeMessages();
    466         } else {
    467             mMirror = isCameraFrontFacing();
    468             String[] defaultFocusModesStrings = mActivity.getResources().getStringArray(
    469                     R.array.pref_camera_focusmode_default_array);
    470             CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier();
    471             ArrayList<CameraCapabilities.FocusMode> defaultFocusModes =
    472                     new ArrayList<CameraCapabilities.FocusMode>();
    473             for (String modeString : defaultFocusModesStrings) {
    474                 CameraCapabilities.FocusMode mode = stringifier.focusModeFromString(modeString);
    475                 if (mode != null) {
    476                     defaultFocusModes.add(mode);
    477                 }
    478             }
    479             mFocusManager = new FocusOverlayManager(mAppController,
    480                     defaultFocusModes, mCameraCapabilities, this, mMirror,
    481                     mActivity.getMainLooper(), mUI.getFocusRing());
    482         }
    483         mAppController.addPreviewAreaSizeChangedListener(mFocusManager);
    484     }
    485 
    486     @Override
    487     public void onOrientationChanged(OrientationManager orientationManager,
    488                                      OrientationManager.DeviceOrientation deviceOrientation) {
    489         mUI.onOrientationChanged(orientationManager, deviceOrientation);
    490     }
    491 
    492     private final ButtonManager.ButtonCallback mFlashCallback =
    493         new ButtonManager.ButtonCallback() {
    494             @Override
    495             public void onStateChanged(int state) {
    496                 if (mPaused) {
    497                     return;
    498                 }
    499                 // Update flash parameters.
    500                 enableTorchMode(true);
    501             }
    502         };
    503 
    504     private final ButtonManager.ButtonCallback mCameraCallback =
    505         new ButtonManager.ButtonCallback() {
    506             @Override
    507             public void onStateChanged(int state) {
    508                 if (mPaused || mAppController.getCameraProvider().waitingForCamera()) {
    509                     return;
    510                 }
    511                 ButtonManager buttonManager = mActivity.getButtonManager();
    512                 buttonManager.disableCameraButtonAndBlock();
    513                 mPendingSwitchCameraId = state;
    514                 Log.d(TAG, "Start to copy texture.");
    515 
    516                 // Disable all camera controls.
    517                 mSwitchingCamera = true;
    518                 switchCamera();
    519             }
    520         };
    521 
    522     private final View.OnClickListener mCancelCallback = new View.OnClickListener() {
    523         @Override
    524         public void onClick(View v) {
    525             onReviewCancelClicked(v);
    526         }
    527     };
    528 
    529     private final View.OnClickListener mDoneCallback = new View.OnClickListener() {
    530         @Override
    531         public void onClick(View v) {
    532             onReviewDoneClicked(v);
    533         }
    534     };
    535     private final View.OnClickListener mReviewCallback = new View.OnClickListener() {
    536         @Override
    537         public void onClick(View v) {
    538             onReviewPlayClicked(v);
    539         }
    540     };
    541 
    542     @Override
    543     public void hardResetSettings(SettingsManager settingsManager) {
    544         // VideoModule does not need to hard reset any settings.
    545     }
    546 
    547     @Override
    548     public HardwareSpec getHardwareSpec() {
    549         if (mHardwareSpec == null) {
    550             mHardwareSpec = (mCameraSettings != null ?
    551                     new HardwareSpecImpl(getCameraProvider(), mCameraCapabilities,
    552                             mAppController.getCameraFeatureConfig(), isCameraFrontFacing()) : null);
    553         }
    554         return mHardwareSpec;
    555     }
    556 
    557     @Override
    558     public CameraAppUI.BottomBarUISpec getBottomBarSpec() {
    559         CameraAppUI.BottomBarUISpec bottomBarSpec = new CameraAppUI.BottomBarUISpec();
    560 
    561         bottomBarSpec.enableCamera = true;
    562         bottomBarSpec.cameraCallback = mCameraCallback;
    563         bottomBarSpec.enableTorchFlash = true;
    564         bottomBarSpec.flashCallback = mFlashCallback;
    565         bottomBarSpec.hideHdr = true;
    566         bottomBarSpec.enableGridLines = true;
    567         bottomBarSpec.enableExposureCompensation = false;
    568         bottomBarSpec.isExposureCompensationSupported = false;
    569 
    570         if (isVideoCaptureIntent()) {
    571             bottomBarSpec.showCancel = true;
    572             bottomBarSpec.cancelCallback = mCancelCallback;
    573             bottomBarSpec.showDone = true;
    574             bottomBarSpec.doneCallback = mDoneCallback;
    575             bottomBarSpec.showReview = true;
    576             bottomBarSpec.reviewCallback = mReviewCallback;
    577         }
    578 
    579         return bottomBarSpec;
    580     }
    581 
    582     @Override
    583     public void onCameraAvailable(CameraProxy cameraProxy) {
    584         if (cameraProxy == null) {
    585             Log.w(TAG, "onCameraAvailable returns a null CameraProxy object");
    586             return;
    587         }
    588         mCameraDevice = cameraProxy;
    589         mCameraCapabilities = mCameraDevice.getCapabilities();
    590         mAppController.getCameraAppUI().showAccessibilityZoomUI(
    591                 mCameraCapabilities.getMaxZoomRatio());
    592         mCameraSettings = mCameraDevice.getSettings();
    593         mFocusAreaSupported = mCameraCapabilities.supports(CameraCapabilities.Feature.FOCUS_AREA);
    594         mMeteringAreaSupported =
    595                 mCameraCapabilities.supports(CameraCapabilities.Feature.METERING_AREA);
    596         readVideoPreferences();
    597         updateDesiredPreviewSize();
    598         resizeForPreviewAspectRatio();
    599         initializeFocusManager();
    600         // TODO: Having focus overlay manager caching the parameters is prone to error,
    601         // we should consider passing the parameters to focus overlay to ensure the
    602         // parameters are up to date.
    603         mFocusManager.updateCapabilities(mCameraCapabilities);
    604 
    605         startPreview();
    606         initializeVideoSnapshot();
    607         mUI.initializeZoom(mCameraSettings, mCameraCapabilities);
    608         initializeControlByIntent();
    609 
    610         mHardwareSpec = new HardwareSpecImpl(getCameraProvider(), mCameraCapabilities,
    611                 mAppController.getCameraFeatureConfig(), isCameraFrontFacing());
    612 
    613         ButtonManager buttonManager = mActivity.getButtonManager();
    614         buttonManager.enableCameraButton();
    615     }
    616 
    617     private void startPlayVideoActivity() {
    618         Intent intent = new Intent(Intent.ACTION_VIEW);
    619         intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    620         intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat));
    621         try {
    622             mActivity.launchActivityByIntent(intent);
    623         } catch (ActivityNotFoundException ex) {
    624             Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex);
    625         }
    626     }
    627 
    628     @Override
    629     public void onReviewPlayClicked(View v) {
    630         startPlayVideoActivity();
    631     }
    632 
    633     @Override
    634     public void onReviewDoneClicked(View v) {
    635         mIsInReviewMode = false;
    636         doReturnToCaller(true);
    637     }
    638 
    639     @Override
    640     public void onReviewCancelClicked(View v) {
    641         // TODO: It should be better to not even insert the URI at all before we
    642         // confirm done in review, which means we need to handle temporary video
    643         // files in a quite different way than we currently had.
    644         // Make sure we don't delete the Uri sent from the video capture intent.
    645         if (mCurrentVideoUriFromMediaSaved) {
    646             mContentResolver.delete(mCurrentVideoUri, null, null);
    647         }
    648         mIsInReviewMode = false;
    649         doReturnToCaller(false);
    650     }
    651 
    652     @Override
    653     public boolean isInReviewMode() {
    654         return mIsInReviewMode;
    655     }
    656 
    657     private void onStopVideoRecording() {
    658         mAppController.getCameraAppUI().setSwipeEnabled(true);
    659         boolean recordFail = stopVideoRecording();
    660         if (mIsVideoCaptureIntent) {
    661             if (mQuickCapture) {
    662                 doReturnToCaller(!recordFail);
    663             } else if (!recordFail) {
    664                 showCaptureResult();
    665             }
    666         } else if (!recordFail){
    667             // Start capture animation.
    668             if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
    669                 // The capture animation is disabled on ICS because we use SurfaceView
    670                 // for preview during recording. When the recording is done, we switch
    671                 // back to use SurfaceTexture for preview and we need to stop then start
    672                 // the preview. This will cause the preview flicker since the preview
    673                 // will not be continuous for a short period of time.
    674                 mAppController.startFlashAnimation(false);
    675             }
    676         }
    677     }
    678 
    679     public void onVideoSaved() {
    680         if (mIsVideoCaptureIntent) {
    681             showCaptureResult();
    682         }
    683     }
    684 
    685     public void onProtectiveCurtainClick(View v) {
    686         // Consume clicks
    687     }
    688 
    689     @Override
    690     public void onShutterButtonClick() {
    691         if (mSwitchingCamera) {
    692             return;
    693         }
    694         boolean stop = mMediaRecorderRecording;
    695 
    696         if (stop) {
    697             // CameraAppUI mishandles mode option enable/disable
    698             // for video, override that
    699             mAppController.getCameraAppUI().enableModeOptions();
    700             onStopVideoRecording();
    701         } else {
    702             // CameraAppUI mishandles mode option enable/disable
    703             // for video, override that
    704             mAppController.getCameraAppUI().disableModeOptions();
    705             startVideoRecording();
    706         }
    707         mAppController.setShutterEnabled(false);
    708         if (mCameraSettings != null) {
    709             mFocusManager.onShutterUp(mCameraSettings.getCurrentFocusMode());
    710         }
    711 
    712         // Keep the shutter button disabled when in video capture intent
    713         // mode and recording is stopped. It'll be re-enabled when
    714         // re-take button is clicked.
    715         if (!(mIsVideoCaptureIntent && stop)) {
    716             mHandler.sendEmptyMessageDelayed(MSG_ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT);
    717         }
    718     }
    719 
    720     @Override
    721     public void onShutterCoordinate(TouchCoordinate coord) {
    722         // Do nothing.
    723     }
    724 
    725     @Override
    726     public void onShutterButtonFocus(boolean pressed) {
    727         // TODO: Remove this when old camera controls are removed from the UI.
    728     }
    729 
    730     private void readVideoPreferences() {
    731         // The preference stores values from ListPreference and is thus string type for all values.
    732         // We need to convert it to int manually.
    733         SettingsManager settingsManager = mActivity.getSettingsManager();
    734         String videoQualityKey = isCameraFrontFacing() ? Keys.KEY_VIDEO_QUALITY_FRONT
    735             : Keys.KEY_VIDEO_QUALITY_BACK;
    736         String videoQuality = settingsManager
    737                 .getString(SettingsManager.SCOPE_GLOBAL, videoQualityKey);
    738         int quality = SettingsUtil.getVideoQuality(videoQuality, mCameraId);
    739         Log.d(TAG, "Selected video quality for '" + videoQuality + "' is " + quality);
    740 
    741         // Set video quality.
    742         Intent intent = mActivity.getIntent();
    743         if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
    744             int extraVideoQuality =
    745                     intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
    746             if (extraVideoQuality > 0) {
    747                 quality = CamcorderProfile.QUALITY_HIGH;
    748             } else {  // 0 is mms.
    749                 quality = CamcorderProfile.QUALITY_LOW;
    750             }
    751         }
    752 
    753         // Set video duration limit. The limit is read from the preference,
    754         // unless it is specified in the intent.
    755         if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
    756             int seconds =
    757                     intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0);
    758             mMaxVideoDurationInMs = 1000 * seconds;
    759         } else {
    760             mMaxVideoDurationInMs = SettingsUtil.getMaxVideoDuration(mActivity
    761                     .getAndroidContext());
    762         }
    763 
    764         // If quality is not supported, request QUALITY_HIGH which is always supported.
    765         if (CamcorderProfile.hasProfile(mCameraId, quality) == false) {
    766             quality = CamcorderProfile.QUALITY_HIGH;
    767         }
    768         mProfile = CamcorderProfile.get(mCameraId, quality);
    769         mPreferenceRead = true;
    770     }
    771 
    772     /**
    773      * Calculates and sets local class variables for Desired Preview sizes.
    774      * This function should be called after every change in preview camera
    775      * resolution and/or before the preview starts. Note that these values still
    776      * need to be pushed to the CameraSettings to actually change the preview
    777      * resolution.  Does nothing when camera pointer is null.
    778      */
    779     private void updateDesiredPreviewSize() {
    780         if (mCameraDevice == null) {
    781             return;
    782         }
    783 
    784         mCameraSettings = mCameraDevice.getSettings();
    785         Point desiredPreviewSize = getDesiredPreviewSize(
    786               mCameraCapabilities, mProfile, mUI.getPreviewScreenSize());
    787         mDesiredPreviewWidth = desiredPreviewSize.x;
    788         mDesiredPreviewHeight = desiredPreviewSize.y;
    789         mUI.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
    790         Log.v(TAG, "Updated DesiredPreview=" + mDesiredPreviewWidth + "x"
    791                 + mDesiredPreviewHeight);
    792     }
    793 
    794     /**
    795      * Calculates the preview size and stores it in mDesiredPreviewWidth and
    796      * mDesiredPreviewHeight.
    797      *
    798      * <p>This function checks {@link
    799      * com.android.camera.cameradevice.CameraCapabilities#getPreferredPreviewSizeForVideo()}
    800      * but also considers the current preview area size on screen and make sure
    801      * the final preview size will not be smaller than 1/2 of the current
    802      * on screen preview area in terms of their short sides.  This function has
    803      * highest priority of WYSIWYG, 1:1 matching as its best match, even if
    804      * there's a larger preview that meets the condition above. </p>
    805      *
    806      * @return The preferred preview size or {@code null} if the camera is not
    807      *         opened yet.
    808      */
    809     private static Point getDesiredPreviewSize(CameraCapabilities capabilities,
    810           CamcorderProfile profile, Point previewScreenSize) {
    811         if (capabilities.getSupportedVideoSizes() == null) {
    812             // Driver doesn't support separate outputs for preview and video.
    813             return new Point(profile.videoFrameWidth, profile.videoFrameHeight);
    814         }
    815 
    816         final int previewScreenShortSide = (previewScreenSize.x < previewScreenSize.y ?
    817                 previewScreenSize.x : previewScreenSize.y);
    818         List<Size> sizes = Size.convert(capabilities.getSupportedPreviewSizes());
    819         Size preferred = new Size(capabilities.getPreferredPreviewSizeForVideo());
    820         final int preferredPreviewSizeShortSide = (preferred.width() < preferred.height() ?
    821                 preferred.width() : preferred.height());
    822         if (preferredPreviewSizeShortSide * 2 < previewScreenShortSide) {
    823             preferred = new Size(profile.videoFrameWidth, profile.videoFrameHeight);
    824         }
    825         int product = preferred.width() * preferred.height();
    826         Iterator<Size> it = sizes.iterator();
    827         // Remove the preview sizes that are not preferred.
    828         while (it.hasNext()) {
    829             Size size = it.next();
    830             if (size.width() * size.height() > product) {
    831                 it.remove();
    832             }
    833         }
    834 
    835         // Take highest priority for WYSIWYG when the preview exactly matches
    836         // video frame size.  The variable sizes is assumed to be filtered
    837         // for sizes beyond the UI size.
    838         for (Size size : sizes) {
    839             if (size.width() == profile.videoFrameWidth
    840                     && size.height() == profile.videoFrameHeight) {
    841                 Log.v(TAG, "Selected =" + size.width() + "x" + size.height()
    842                            + " on WYSIWYG Priority");
    843                 return new Point(profile.videoFrameWidth, profile.videoFrameHeight);
    844             }
    845         }
    846 
    847         Size optimalSize = CameraUtil.getOptimalPreviewSize(sizes,
    848                 (double) profile.videoFrameWidth / profile.videoFrameHeight);
    849         return new Point(optimalSize.width(), optimalSize.height());
    850     }
    851 
    852     private void resizeForPreviewAspectRatio() {
    853         mUI.setAspectRatio((float) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
    854     }
    855 
    856     private void installIntentFilter() {
    857         // install an intent filter to receive SD card related events.
    858         IntentFilter intentFilter =
    859                 new IntentFilter(Intent.ACTION_MEDIA_EJECT);
    860         intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
    861         intentFilter.addDataScheme("file");
    862         mReceiver = new MyBroadcastReceiver();
    863         mActivity.registerReceiver(mReceiver, intentFilter);
    864     }
    865 
    866     private void setDisplayOrientation() {
    867         mDisplayRotation = CameraUtil.getDisplayRotation();
    868         Characteristics info =
    869                 mActivity.getCameraProvider().getCharacteristics(mCameraId);
    870         mCameraDisplayOrientation = info.getPreviewOrientation(mDisplayRotation);
    871         // Change the camera display orientation
    872         if (mCameraDevice != null) {
    873             mCameraDevice.setDisplayOrientation(mDisplayRotation);
    874         }
    875         if (mFocusManager != null) {
    876             mFocusManager.setDisplayOrientation(mCameraDisplayOrientation);
    877         }
    878     }
    879 
    880     @Override
    881     public void updateCameraOrientation() {
    882         if (mMediaRecorderRecording) {
    883             return;
    884         }
    885         if (mDisplayRotation != CameraUtil.getDisplayRotation()) {
    886             setDisplayOrientation();
    887         }
    888     }
    889 
    890     @Override
    891     public void updatePreviewAspectRatio(float aspectRatio) {
    892         mAppController.updatePreviewAspectRatio(aspectRatio);
    893     }
    894 
    895     /**
    896      * Returns current Zoom value, with 1.0 as the value for no zoom.
    897      */
    898     private float currentZoomValue() {
    899         return mCameraSettings.getCurrentZoomRatio();
    900     }
    901 
    902     @Override
    903     public void onZoomChanged(float ratio) {
    904         // Not useful to change zoom value when the activity is paused.
    905         if (mPaused) {
    906             return;
    907         }
    908         mZoomValue = ratio;
    909         if (mCameraSettings == null || mCameraDevice == null) {
    910             return;
    911         }
    912         // Set zoom parameters asynchronously
    913         mCameraSettings.setZoomRatio(mZoomValue);
    914         mCameraDevice.applySettings(mCameraSettings);
    915     }
    916 
    917     private void startPreview() {
    918         Log.i(TAG, "startPreview");
    919 
    920         SurfaceTexture surfaceTexture = mActivity.getCameraAppUI().getSurfaceTexture();
    921         if (!mPreferenceRead || surfaceTexture == null || mPaused == true ||
    922                 mCameraDevice == null) {
    923             return;
    924         }
    925 
    926         if (mPreviewing == true) {
    927             stopPreview();
    928         }
    929 
    930         setDisplayOrientation();
    931         mCameraDevice.setDisplayOrientation(mDisplayRotation);
    932         setCameraParameters();
    933 
    934         if (mFocusManager != null) {
    935             // If the focus mode is continuous autofocus, call cancelAutoFocus
    936             // to resume it because it may have been paused by autoFocus call.
    937             CameraCapabilities.FocusMode focusMode =
    938                     mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode());
    939             if (focusMode == CameraCapabilities.FocusMode.CONTINUOUS_PICTURE) {
    940                 mCameraDevice.cancelAutoFocus();
    941             }
    942         }
    943 
    944         // This is to notify app controller that preview will start next, so app
    945         // controller can set preview callbacks if needed. This has to happen before
    946         // preview is started as a workaround of the framework issue related to preview
    947         // callbacks that causes preview stretch and crash. (More details see b/12210027
    948         // and b/12591410. Don't apply this to L, see b/16649297.
    949         if (!ApiHelper.isLOrHigher()) {
    950             Log.v(TAG, "calling onPreviewReadyToStart to set one shot callback");
    951             mAppController.onPreviewReadyToStart();
    952         } else {
    953             Log.v(TAG, "on L, no one shot callback necessary");
    954         }
    955         try {
    956             mCameraDevice.setPreviewTexture(surfaceTexture);
    957             mCameraDevice.startPreviewWithCallback(new Handler(Looper.getMainLooper()),
    958                     new CameraAgent.CameraStartPreviewCallback() {
    959                 @Override
    960                 public void onPreviewStarted() {
    961                     VideoModule.this.onPreviewStarted();
    962                 }
    963             });
    964             mPreviewing = true;
    965         } catch (Throwable ex) {
    966             closeCamera();
    967             throw new RuntimeException("startPreview failed", ex);
    968         }
    969     }
    970 
    971     private void onPreviewStarted() {
    972         mAppController.setShutterEnabled(true);
    973         mAppController.onPreviewStarted();
    974         if (mFocusManager != null) {
    975             mFocusManager.onPreviewStarted();
    976         }
    977     }
    978 
    979     @Override
    980     public void onPreviewInitialDataReceived() {
    981     }
    982 
    983     @Override
    984     public void stopPreview() {
    985         if (!mPreviewing) {
    986             Log.v(TAG, "Skip stopPreview since it's not mPreviewing");
    987             return;
    988         }
    989         if (mCameraDevice == null) {
    990             Log.v(TAG, "Skip stopPreview since mCameraDevice is null");
    991             return;
    992         }
    993 
    994         Log.v(TAG, "stopPreview");
    995         mCameraDevice.stopPreview();
    996         if (mFocusManager != null) {
    997             mFocusManager.onPreviewStopped();
    998         }
    999         mPreviewing = false;
   1000     }
   1001 
   1002     private void closeCamera() {
   1003         Log.i(TAG, "closeCamera");
   1004         if (mCameraDevice == null) {
   1005             Log.d(TAG, "already stopped.");
   1006             return;
   1007         }
   1008         mCameraDevice.setZoomChangeListener(null);
   1009         mActivity.getCameraProvider().releaseCamera(mCameraDevice.getCameraId());
   1010         mCameraDevice = null;
   1011         mPreviewing = false;
   1012         mSnapshotInProgress = false;
   1013         if (mFocusManager != null) {
   1014             mFocusManager.onCameraReleased();
   1015         }
   1016     }
   1017 
   1018     @Override
   1019     public boolean onBackPressed() {
   1020         if (mPaused) {
   1021             return true;
   1022         }
   1023         if (mMediaRecorderRecording) {
   1024             onStopVideoRecording();
   1025             return true;
   1026         } else {
   1027             return false;
   1028         }
   1029     }
   1030 
   1031     @Override
   1032     public boolean onKeyDown(int keyCode, KeyEvent event) {
   1033         // Do not handle any key if the activity is paused.
   1034         if (mPaused) {
   1035             return true;
   1036         }
   1037 
   1038         switch (keyCode) {
   1039             case KeyEvent.KEYCODE_CAMERA:
   1040                 if (event.getRepeatCount() == 0) {
   1041                     onShutterButtonClick();
   1042                     return true;
   1043                 }
   1044             case KeyEvent.KEYCODE_DPAD_CENTER:
   1045                 if (event.getRepeatCount() == 0) {
   1046                     onShutterButtonClick();
   1047                     return true;
   1048                 }
   1049             case KeyEvent.KEYCODE_MENU:
   1050                 // Consume menu button presses during capture.
   1051                 return mMediaRecorderRecording;
   1052         }
   1053         return false;
   1054     }
   1055 
   1056     @Override
   1057     public boolean onKeyUp(int keyCode, KeyEvent event) {
   1058         switch (keyCode) {
   1059             case KeyEvent.KEYCODE_CAMERA:
   1060                 onShutterButtonClick();
   1061                 return true;
   1062             case KeyEvent.KEYCODE_MENU:
   1063                 // Consume menu button presses during capture.
   1064                 return mMediaRecorderRecording;
   1065         }
   1066         return false;
   1067     }
   1068 
   1069     @Override
   1070     public boolean isVideoCaptureIntent() {
   1071         String action = mActivity.getIntent().getAction();
   1072         return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action));
   1073     }
   1074 
   1075     private void doReturnToCaller(boolean valid) {
   1076         Intent resultIntent = new Intent();
   1077         int resultCode;
   1078         if (valid) {
   1079             resultCode = Activity.RESULT_OK;
   1080             resultIntent.setData(mCurrentVideoUri);
   1081             resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   1082         } else {
   1083             resultCode = Activity.RESULT_CANCELED;
   1084         }
   1085         mActivity.setResultEx(resultCode, resultIntent);
   1086         mActivity.finish();
   1087     }
   1088 
   1089     private void cleanupEmptyFile() {
   1090         if (mVideoFilename != null) {
   1091             File f = new File(mVideoFilename);
   1092             if (f.length() == 0 && f.delete()) {
   1093                 Log.v(TAG, "Empty video file deleted: " + mVideoFilename);
   1094                 mVideoFilename = null;
   1095             }
   1096         }
   1097     }
   1098 
   1099     // Prepares media recorder.
   1100     private void initializeRecorder() {
   1101         Log.i(TAG, "initializeRecorder: " + Thread.currentThread());
   1102         // If the mCameraDevice is null, then this activity is going to finish
   1103         if (mCameraDevice == null) {
   1104             Log.w(TAG, "null camera proxy, not recording");
   1105             return;
   1106         }
   1107         Intent intent = mActivity.getIntent();
   1108         Bundle myExtras = intent.getExtras();
   1109 
   1110         long requestedSizeLimit = 0;
   1111         closeVideoFileDescriptor();
   1112         mCurrentVideoUriFromMediaSaved = false;
   1113         if (mIsVideoCaptureIntent && myExtras != null) {
   1114             Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
   1115             if (saveUri != null) {
   1116                 try {
   1117                     mVideoFileDescriptor =
   1118                             mContentResolver.openFileDescriptor(saveUri, "rw");
   1119                     mCurrentVideoUri = saveUri;
   1120                 } catch (java.io.FileNotFoundException ex) {
   1121                     // invalid uri
   1122                     Log.e(TAG, ex.toString());
   1123                 }
   1124             }
   1125             requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
   1126         }
   1127         mMediaRecorder = new MediaRecorder();
   1128         // Unlock the camera object before passing it to media recorder.
   1129         mCameraDevice.unlock();
   1130         // We rely here on the fact that the unlock call above is synchronous
   1131         // and blocks until it occurs in the handler thread. Thereby ensuring
   1132         // that we are up to date with handler requests, and if this proxy had
   1133         // ever been released by a prior command, it would be null.
   1134         Camera camera = mCameraDevice.getCamera();
   1135         // If the camera device is null, the camera proxy is stale and recording
   1136         // should be ignored.
   1137         if (camera == null) {
   1138             Log.w(TAG, "null camera within proxy, not recording");
   1139             return;
   1140         }
   1141 
   1142         mMediaRecorder.setCamera(camera);
   1143         mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
   1144         mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
   1145         mMediaRecorder.setProfile(mProfile);
   1146         mMediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
   1147         mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs);
   1148 
   1149         setRecordLocation();
   1150 
   1151         // Set output file.
   1152         // Try Uri in the intent first. If it doesn't exist, use our own
   1153         // instead.
   1154         if (mVideoFileDescriptor != null) {
   1155             mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
   1156         } else {
   1157             generateVideoFilename(mProfile.fileFormat);
   1158             mMediaRecorder.setOutputFile(mVideoFilename);
   1159         }
   1160 
   1161         // Set maximum file size.
   1162         long maxFileSize = mActivity.getStorageSpaceBytes() - Storage.LOW_STORAGE_THRESHOLD_BYTES;
   1163         if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
   1164             maxFileSize = requestedSizeLimit;
   1165         }
   1166 
   1167         try {
   1168             mMediaRecorder.setMaxFileSize(maxFileSize);
   1169         } catch (RuntimeException exception) {
   1170             // We are going to ignore failure of setMaxFileSize here, as
   1171             // a) The composer selected may simply not support it, or
   1172             // b) The underlying media framework may not handle 64-bit range
   1173             // on the size restriction.
   1174         }
   1175 
   1176         int sensorOrientation =
   1177                 mActivity.getCameraProvider().getCharacteristics(mCameraId).getSensorOrientation();
   1178         int deviceOrientation =
   1179                 mAppController.getOrientationManager().getDeviceOrientation().getDegrees();
   1180         int rotation = CameraUtil.getImageRotation(
   1181                 sensorOrientation, deviceOrientation, isCameraFrontFacing());
   1182         mMediaRecorder.setOrientationHint(rotation);
   1183 
   1184         try {
   1185             mMediaRecorder.prepare();
   1186         } catch (IOException e) {
   1187             Log.e(TAG, "prepare failed for " + mVideoFilename, e);
   1188             releaseMediaRecorder();
   1189             throw new RuntimeException(e);
   1190         }
   1191 
   1192         mMediaRecorder.setOnErrorListener(this);
   1193         mMediaRecorder.setOnInfoListener(this);
   1194     }
   1195 
   1196     private static void setCaptureRate(MediaRecorder recorder, double fps) {
   1197         recorder.setCaptureRate(fps);
   1198     }
   1199 
   1200     private void setRecordLocation() {
   1201         Location loc = mLocationManager.getCurrentLocation();
   1202         if (loc != null) {
   1203             mMediaRecorder.setLocation((float) loc.getLatitude(),
   1204                     (float) loc.getLongitude());
   1205         }
   1206     }
   1207 
   1208     private void releaseMediaRecorder() {
   1209         Log.i(TAG, "Releasing media recorder.");
   1210         if (mMediaRecorder != null) {
   1211             cleanupEmptyFile();
   1212             mMediaRecorder.reset();
   1213             mMediaRecorder.release();
   1214             mMediaRecorder = null;
   1215         }
   1216         mVideoFilename = null;
   1217     }
   1218 
   1219     private void generateVideoFilename(int outputFileFormat) {
   1220         long dateTaken = System.currentTimeMillis();
   1221         String title = createName(dateTaken);
   1222         // Used when emailing.
   1223         String filename = title + convertOutputFormatToFileExt(outputFileFormat);
   1224         String mime = convertOutputFormatToMimeType(outputFileFormat);
   1225         String path = Storage.DIRECTORY + '/' + filename;
   1226         String tmpPath = path + ".tmp";
   1227         mCurrentVideoValues = new ContentValues(9);
   1228         mCurrentVideoValues.put(Video.Media.TITLE, title);
   1229         mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename);
   1230         mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken);
   1231         mCurrentVideoValues.put(MediaColumns.DATE_MODIFIED, dateTaken / 1000);
   1232         mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime);
   1233         mCurrentVideoValues.put(Video.Media.DATA, path);
   1234         mCurrentVideoValues.put(Video.Media.WIDTH, mProfile.videoFrameWidth);
   1235         mCurrentVideoValues.put(Video.Media.HEIGHT, mProfile.videoFrameHeight);
   1236         mCurrentVideoValues.put(Video.Media.RESOLUTION,
   1237                 Integer.toString(mProfile.videoFrameWidth) + "x" +
   1238                 Integer.toString(mProfile.videoFrameHeight));
   1239         Location loc = mLocationManager.getCurrentLocation();
   1240         if (loc != null) {
   1241             mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude());
   1242             mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude());
   1243         }
   1244         mVideoFilename = tmpPath;
   1245         Log.v(TAG, "New video filename: " + mVideoFilename);
   1246     }
   1247 
   1248     private void logVideoCapture(long duration) {
   1249         String flashSetting = mActivity.getSettingsManager()
   1250                 .getString(mAppController.getCameraScope(),
   1251                            Keys.KEY_VIDEOCAMERA_FLASH_MODE);
   1252         boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager());
   1253         int width = (Integer) mCurrentVideoValues.get(Video.Media.WIDTH);
   1254         int height = (Integer) mCurrentVideoValues.get(Video.Media.HEIGHT);
   1255         long size = new File(mCurrentVideoFilename).length();
   1256         String name = new File(mCurrentVideoValues.getAsString(Video.Media.DATA)).getName();
   1257         UsageStatistics.instance().videoCaptureDoneEvent(name, duration, isCameraFrontFacing(),
   1258                 currentZoomValue(), width, height, size, flashSetting, gridLinesOn);
   1259     }
   1260 
   1261     private void saveVideo() {
   1262         if (mVideoFileDescriptor == null) {
   1263             long duration = SystemClock.uptimeMillis() - mRecordingStartTime;
   1264             if (duration > 0) {
   1265                 //
   1266             } else {
   1267                 Log.w(TAG, "Video duration <= 0 : " + duration);
   1268             }
   1269             mCurrentVideoValues.put(Video.Media.SIZE, new File(mCurrentVideoFilename).length());
   1270             mCurrentVideoValues.put(Video.Media.DURATION, duration);
   1271             getServices().getMediaSaver().addVideo(mCurrentVideoFilename,
   1272                     mCurrentVideoValues, mOnVideoSavedListener);
   1273             logVideoCapture(duration);
   1274         }
   1275         mCurrentVideoValues = null;
   1276     }
   1277 
   1278     private void deleteVideoFile(String fileName) {
   1279         Log.v(TAG, "Deleting video " + fileName);
   1280         File f = new File(fileName);
   1281         if (!f.delete()) {
   1282             Log.v(TAG, "Could not delete " + fileName);
   1283         }
   1284     }
   1285 
   1286     // from MediaRecorder.OnErrorListener
   1287     @Override
   1288     public void onError(MediaRecorder mr, int what, int extra) {
   1289         Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra);
   1290         if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
   1291             // We may have run out of space on the sdcard.
   1292             stopVideoRecording();
   1293             mActivity.updateStorageSpaceAndHint(null);
   1294         }
   1295     }
   1296 
   1297     // from MediaRecorder.OnInfoListener
   1298     @Override
   1299     public void onInfo(MediaRecorder mr, int what, int extra) {
   1300         if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
   1301             if (mMediaRecorderRecording) {
   1302                 onStopVideoRecording();
   1303             }
   1304         } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
   1305             if (mMediaRecorderRecording) {
   1306                 onStopVideoRecording();
   1307             }
   1308 
   1309             // Show the toast.
   1310             Toast.makeText(mActivity, R.string.video_reach_size_limit,
   1311                     Toast.LENGTH_LONG).show();
   1312         }
   1313     }
   1314 
   1315     /*
   1316      * Make sure we're not recording music playing in the background, ask the
   1317      * MediaPlaybackService to pause playback.
   1318      */
   1319     private void silenceSoundsAndVibrations() {
   1320         // Get the audio focus which causes other music players to stop.
   1321         mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC,
   1322                 AudioManager.AUDIOFOCUS_GAIN);
   1323         // Store current ringer mode so we can set it once video recording is
   1324         // finished.
   1325         mOriginalRingerMode = mAudioManager.getRingerMode();
   1326         // Make sure no system sounds and vibrations happen during video
   1327         // recording.
   1328         mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
   1329     }
   1330 
   1331     private void restoreRingerMode() {
   1332         // First check if ringer mode was changed during the recording. If not,
   1333         // re-set the mode that was set before video recording started.
   1334         if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
   1335             mAudioManager.setRingerMode(mOriginalRingerMode);
   1336         }
   1337     }
   1338 
   1339     // For testing.
   1340     public boolean isRecording() {
   1341         return mMediaRecorderRecording;
   1342     }
   1343 
   1344     private void startVideoRecording() {
   1345         Log.i(TAG, "startVideoRecording: " + Thread.currentThread());
   1346         mUI.cancelAnimations();
   1347         mUI.setSwipingEnabled(false);
   1348         mUI.hidePassiveFocusIndicator();
   1349         mAppController.getCameraAppUI().hideCaptureIndicator();
   1350         mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(true);
   1351 
   1352         mActivity.updateStorageSpaceAndHint(new CameraActivity.OnStorageUpdateDoneListener() {
   1353             @Override
   1354             public void onStorageUpdateDone(long bytes) {
   1355                 if (bytes <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
   1356                     Log.w(TAG, "Storage issue, ignore the start request");
   1357                 } else {
   1358                     if (mCameraDevice == null) {
   1359                         Log.v(TAG, "in storage callback after camera closed");
   1360                         return;
   1361                     }
   1362                     if (mPaused == true) {
   1363                         Log.v(TAG, "in storage callback after module paused");
   1364                         return;
   1365                     }
   1366 
   1367                     // Monkey is so fast so it could trigger startVideoRecording twice. To prevent
   1368                     // app crash (b/17313985), do nothing here for the second storage-checking
   1369                     // callback because recording is already started.
   1370                     if (mMediaRecorderRecording) {
   1371                         Log.v(TAG, "in storage callback after recording started");
   1372                         return;
   1373                     }
   1374 
   1375                     mCurrentVideoUri = null;
   1376 
   1377                     initializeRecorder();
   1378                     if (mMediaRecorder == null) {
   1379                         Log.e(TAG, "Fail to initialize media recorder");
   1380                         return;
   1381                     }
   1382 
   1383                     try {
   1384                         mMediaRecorder.start(); // Recording is now started
   1385                     } catch (RuntimeException e) {
   1386                         Log.e(TAG, "Could not start media recorder. ", e);
   1387                         mAppController.getFatalErrorHandler().onGenericCameraAccessFailure();
   1388                         releaseMediaRecorder();
   1389                         // If start fails, frameworks will not lock the camera for us.
   1390                         mCameraDevice.lock();
   1391                         return;
   1392                     }
   1393                     // Make sure we stop playing sounds and disable the
   1394                     // vibrations during video recording. Post delayed to avoid
   1395                     // silencing the recording start sound.
   1396                     mHandler.postDelayed(new Runnable() {
   1397                         @Override
   1398                         public void run() {
   1399                             silenceSoundsAndVibrations();
   1400                         }
   1401                     }, 250);
   1402 
   1403                     mAppController.getCameraAppUI().setSwipeEnabled(false);
   1404 
   1405                     // The parameters might have been altered by MediaRecorder already.
   1406                     // We need to force mCameraDevice to refresh before getting it.
   1407                     mCameraDevice.refreshSettings();
   1408                     // The parameters may have been changed by MediaRecorder upon starting
   1409                     // recording. We need to alter the parameters if we support camcorder
   1410                     // zoom. To reduce latency when setting the parameters during zoom, we
   1411                     // update the settings here once.
   1412                     mCameraSettings = mCameraDevice.getSettings();
   1413 
   1414                     mMediaRecorderRecording = true;
   1415                     mActivity.lockOrientation();
   1416                     mRecordingStartTime = SystemClock.uptimeMillis();
   1417 
   1418                     // A special case of mode options closing: during capture it should
   1419                     // not be possible to change mode state.
   1420                     mAppController.getCameraAppUI().hideModeOptions();
   1421                     mAppController.getCameraAppUI().animateBottomBarToVideoStop(R.drawable.ic_stop);
   1422                     mUI.showRecordingUI(true);
   1423 
   1424                     setFocusParameters();
   1425 
   1426                     updateRecordingTime();
   1427                     mActivity.enableKeepScreenOn(true);
   1428                 }
   1429             }
   1430         });
   1431     }
   1432 
   1433     private Bitmap getVideoThumbnail() {
   1434         Bitmap bitmap = null;
   1435         if (mVideoFileDescriptor != null) {
   1436             bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
   1437                     mDesiredPreviewWidth);
   1438         } else if (mCurrentVideoUri != null) {
   1439             try {
   1440                 mVideoFileDescriptor = mContentResolver.openFileDescriptor(mCurrentVideoUri, "r");
   1441                 bitmap = Thumbnail.createVideoThumbnailBitmap(
   1442                         mVideoFileDescriptor.getFileDescriptor(), mDesiredPreviewWidth);
   1443             } catch (java.io.FileNotFoundException ex) {
   1444                 // invalid uri
   1445                 Log.e(TAG, ex.toString());
   1446             }
   1447         }
   1448 
   1449         if (bitmap != null) {
   1450             // MetadataRetriever already rotates the thumbnail. We should rotate
   1451             // it to match the UI orientation (and mirror if it is front-facing camera).
   1452             bitmap = CameraUtil.rotateAndMirror(bitmap, 0, isCameraFrontFacing());
   1453         }
   1454         return bitmap;
   1455     }
   1456 
   1457     private void showCaptureResult() {
   1458         mIsInReviewMode = true;
   1459         Bitmap bitmap = getVideoThumbnail();
   1460         if (bitmap != null) {
   1461             mUI.showReviewImage(bitmap);
   1462         }
   1463         mUI.showReviewControls();
   1464     }
   1465 
   1466     private boolean stopVideoRecording() {
   1467         // Do nothing if camera device is still capturing photo. Monkey test can trigger app crashes
   1468         // (b/17313985) without this check. Crash could also be reproduced by continuously tapping
   1469         // on shutter button and preview with two fingers.
   1470         if (mSnapshotInProgress) {
   1471             Log.v(TAG, "Skip stopVideoRecording since snapshot in progress");
   1472             return true;
   1473         }
   1474         Log.v(TAG, "stopVideoRecording");
   1475 
   1476         // Re-enable sound as early as possible to avoid interfering with stop
   1477         // recording sound.
   1478         restoreRingerMode();
   1479 
   1480         mUI.setSwipingEnabled(true);
   1481         mUI.showPassiveFocusIndicator();
   1482         mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(false);
   1483 
   1484         boolean fail = false;
   1485         if (mMediaRecorderRecording) {
   1486             boolean shouldAddToMediaStoreNow = false;
   1487 
   1488             try {
   1489                 mMediaRecorder.setOnErrorListener(null);
   1490                 mMediaRecorder.setOnInfoListener(null);
   1491                 mMediaRecorder.stop();
   1492                 shouldAddToMediaStoreNow = true;
   1493                 mCurrentVideoFilename = mVideoFilename;
   1494                 Log.v(TAG, "stopVideoRecording: current video filename: " + mCurrentVideoFilename);
   1495             } catch (RuntimeException e) {
   1496                 Log.e(TAG, "stop fail",  e);
   1497                 if (mVideoFilename != null) {
   1498                     deleteVideoFile(mVideoFilename);
   1499                 }
   1500                 fail = true;
   1501             }
   1502             mMediaRecorderRecording = false;
   1503             mActivity.unlockOrientation();
   1504 
   1505             // If the activity is paused, this means activity is interrupted
   1506             // during recording. Release the camera as soon as possible because
   1507             // face unlock or other applications may need to use the camera.
   1508             if (mPaused) {
   1509                 // b/16300704: Monkey is fast so it could pause the module while recording.
   1510                 // stopPreview should definitely be called before switching off.
   1511                 stopPreview();
   1512                 closeCamera();
   1513             }
   1514 
   1515             mUI.showRecordingUI(false);
   1516             // The orientation was fixed during video recording. Now make it
   1517             // reflect the device orientation as video recording is stopped.
   1518             mUI.setOrientationIndicator(0, true);
   1519             mActivity.enableKeepScreenOn(false);
   1520             if (shouldAddToMediaStoreNow && !fail) {
   1521                 if (mVideoFileDescriptor == null) {
   1522                     saveVideo();
   1523                 } else if (mIsVideoCaptureIntent) {
   1524                     // if no file save is needed, we can show the post capture UI now
   1525                     showCaptureResult();
   1526                 }
   1527             }
   1528         }
   1529         // release media recorder
   1530         releaseMediaRecorder();
   1531 
   1532         mAppController.getCameraAppUI().showModeOptions();
   1533         mAppController.getCameraAppUI().animateBottomBarToFullSize(mShutterIconId);
   1534         if (!mPaused && mCameraDevice != null) {
   1535             setFocusParameters();
   1536             mCameraDevice.lock();
   1537             if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
   1538                 stopPreview();
   1539                 // Switch back to use SurfaceTexture for preview.
   1540                 startPreview();
   1541             }
   1542             // Update the parameters here because the parameters might have been altered
   1543             // by MediaRecorder.
   1544             mCameraSettings = mCameraDevice.getSettings();
   1545         }
   1546 
   1547         // Check this in advance of each shot so we don't add to shutter
   1548         // latency. It's true that someone else could write to the SD card
   1549         // in the mean time and fill it, but that could have happened
   1550         // between the shutter press and saving the file too.
   1551         mActivity.updateStorageSpaceAndHint(null);
   1552 
   1553         return fail;
   1554     }
   1555 
   1556     private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
   1557         long seconds = milliSeconds / 1000; // round down to compute seconds
   1558         long minutes = seconds / 60;
   1559         long hours = minutes / 60;
   1560         long remainderMinutes = minutes - (hours * 60);
   1561         long remainderSeconds = seconds - (minutes * 60);
   1562 
   1563         StringBuilder timeStringBuilder = new StringBuilder();
   1564 
   1565         // Hours
   1566         if (hours > 0) {
   1567             if (hours < 10) {
   1568                 timeStringBuilder.append('0');
   1569             }
   1570             timeStringBuilder.append(hours);
   1571 
   1572             timeStringBuilder.append(':');
   1573         }
   1574 
   1575         // Minutes
   1576         if (remainderMinutes < 10) {
   1577             timeStringBuilder.append('0');
   1578         }
   1579         timeStringBuilder.append(remainderMinutes);
   1580         timeStringBuilder.append(':');
   1581 
   1582         // Seconds
   1583         if (remainderSeconds < 10) {
   1584             timeStringBuilder.append('0');
   1585         }
   1586         timeStringBuilder.append(remainderSeconds);
   1587 
   1588         // Centi seconds
   1589         if (displayCentiSeconds) {
   1590             timeStringBuilder.append('.');
   1591             long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
   1592             if (remainderCentiSeconds < 10) {
   1593                 timeStringBuilder.append('0');
   1594             }
   1595             timeStringBuilder.append(remainderCentiSeconds);
   1596         }
   1597 
   1598         return timeStringBuilder.toString();
   1599     }
   1600 
   1601     private void updateRecordingTime() {
   1602         if (!mMediaRecorderRecording) {
   1603             return;
   1604         }
   1605         long now = SystemClock.uptimeMillis();
   1606         long delta = now - mRecordingStartTime;
   1607 
   1608         // Starting a minute before reaching the max duration
   1609         // limit, we'll countdown the remaining time instead.
   1610         boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
   1611                 && delta >= mMaxVideoDurationInMs - 60000);
   1612 
   1613         long deltaAdjusted = delta;
   1614         if (countdownRemainingTime) {
   1615             deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
   1616         }
   1617         String text;
   1618 
   1619         long targetNextUpdateDelay;
   1620 
   1621         text = millisecondToTimeString(deltaAdjusted, false);
   1622         targetNextUpdateDelay = 1000;
   1623 
   1624         mUI.setRecordingTime(text);
   1625 
   1626         if (mRecordingTimeCountsDown != countdownRemainingTime) {
   1627             // Avoid setting the color on every update, do it only
   1628             // when it needs changing.
   1629             mRecordingTimeCountsDown = countdownRemainingTime;
   1630 
   1631             int color = mActivity.getResources().getColor(R.color.recording_time_remaining_text);
   1632 
   1633             mUI.setRecordingTimeTextColor(color);
   1634         }
   1635 
   1636         long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
   1637         mHandler.sendEmptyMessageDelayed(MSG_UPDATE_RECORD_TIME, actualNextUpdateDelay);
   1638     }
   1639 
   1640     private static boolean isSupported(String value, List<String> supported) {
   1641         return supported == null ? false : supported.indexOf(value) >= 0;
   1642     }
   1643 
   1644     @SuppressWarnings("deprecation")
   1645     private void setCameraParameters() {
   1646         SettingsManager settingsManager = mActivity.getSettingsManager();
   1647 
   1648         // Update Desired Preview size in case video camera resolution has changed.
   1649         updateDesiredPreviewSize();
   1650 
   1651         Size previewSize = new Size(mDesiredPreviewWidth, mDesiredPreviewHeight);
   1652         mCameraSettings.setPreviewSize(previewSize.toPortabilitySize());
   1653         // This is required for Samsung SGH-I337 and probably other Samsung S4 versions
   1654         if (Build.BRAND.toLowerCase().contains("samsung")) {
   1655             mCameraSettings.setSetting("video-size",
   1656                     mProfile.videoFrameWidth + "x" + mProfile.videoFrameHeight);
   1657         }
   1658         int[] fpsRange =
   1659                 CameraUtil.getMaxPreviewFpsRange(mCameraCapabilities.getSupportedPreviewFpsRange());
   1660         if (fpsRange.length > 0) {
   1661             mCameraSettings.setPreviewFpsRange(fpsRange[0], fpsRange[1]);
   1662         } else {
   1663             mCameraSettings.setPreviewFrameRate(mProfile.videoFrameRate);
   1664         }
   1665 
   1666         enableTorchMode(Keys.isCameraBackFacing(settingsManager, mAppController.getModuleScope()));
   1667 
   1668         // Set zoom.
   1669         if (mCameraCapabilities.supports(CameraCapabilities.Feature.ZOOM)) {
   1670             mCameraSettings.setZoomRatio(mZoomValue);
   1671         }
   1672         updateFocusParameters();
   1673 
   1674         mCameraSettings.setRecordingHintEnabled(true);
   1675 
   1676         if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_STABILIZATION)) {
   1677             mCameraSettings.setVideoStabilization(true);
   1678         }
   1679 
   1680         // Set picture size.
   1681         // The logic here is different from the logic in still-mode camera.
   1682         // There we determine the preview size based on the picture size, but
   1683         // here we determine the picture size based on the preview size.
   1684         List<Size> supported = Size.convert(mCameraCapabilities.getSupportedPhotoSizes());
   1685         Size optimalSize = CameraUtil.getOptimalVideoSnapshotPictureSize(supported,
   1686                 mDesiredPreviewWidth, mDesiredPreviewHeight);
   1687         Size original = new Size(mCameraSettings.getCurrentPhotoSize());
   1688         if (!original.equals(optimalSize)) {
   1689             mCameraSettings.setPhotoSize(optimalSize.toPortabilitySize());
   1690         }
   1691         Log.d(TAG, "Video snapshot size is " + optimalSize);
   1692 
   1693         // Set JPEG quality.
   1694         int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
   1695                 CameraProfile.QUALITY_HIGH);
   1696         mCameraSettings.setPhotoJpegCompressionQuality(jpegQuality);
   1697 
   1698         if (mCameraDevice != null) {
   1699             mCameraDevice.applySettings(mCameraSettings);
   1700             // Nexus 5 through KitKat 4.4.2 requires a second call to
   1701             // .setParameters() for frame rate settings to take effect.
   1702             mCameraDevice.applySettings(mCameraSettings);
   1703         }
   1704 
   1705         // Update UI based on the new parameters.
   1706         mUI.updateOnScreenIndicators(mCameraSettings);
   1707     }
   1708 
   1709     private void updateFocusParameters() {
   1710         // Set continuous autofocus. During recording, we use "continuous-video"
   1711         // auto focus mode to ensure smooth focusing. Whereas during preview (i.e.
   1712         // before recording starts) we use "continuous-picture" auto focus mode
   1713         // for faster but slightly jittery focusing.
   1714         Set<CameraCapabilities.FocusMode> supportedFocus = mCameraCapabilities
   1715                 .getSupportedFocusModes();
   1716         if (mMediaRecorderRecording) {
   1717             if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO)) {
   1718                 mCameraSettings.setFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
   1719                 mFocusManager.overrideFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
   1720             } else {
   1721                 mFocusManager.overrideFocusMode(null);
   1722             }
   1723         } else {
   1724             // FIXME(b/16984793): This is broken. For some reasons, CONTINUOUS_PICTURE is not on
   1725             // when preview starts.
   1726             mFocusManager.overrideFocusMode(null);
   1727             if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_PICTURE)) {
   1728                 mCameraSettings.setFocusMode(
   1729                         mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode()));
   1730                 if (mFocusAreaSupported) {
   1731                     mCameraSettings.setFocusAreas(mFocusManager.getFocusAreas());
   1732                 }
   1733             }
   1734         }
   1735         updateAutoFocusMoveCallback();
   1736     }
   1737 
   1738     @Override
   1739     public void resume() {
   1740         if (isVideoCaptureIntent()) {
   1741             mDontResetIntentUiOnResume = mPaused;
   1742         }
   1743 
   1744         mPaused = false;
   1745         installIntentFilter();
   1746         mAppController.setShutterEnabled(false);
   1747         mZoomValue = 1.0f;
   1748 
   1749         OrientationManager orientationManager = mAppController.getOrientationManager();
   1750         orientationManager.addOnOrientationChangeListener(this);
   1751         mUI.onOrientationChanged(orientationManager, orientationManager.getDeviceOrientation());
   1752 
   1753         showVideoSnapshotUI(false);
   1754 
   1755         if (!mPreviewing) {
   1756             requestCamera(mCameraId);
   1757         } else {
   1758             // preview already started
   1759             mAppController.setShutterEnabled(true);
   1760         }
   1761 
   1762         if (mFocusManager != null) {
   1763             // If camera is not open when resume is called, focus manager will not
   1764             // be initialized yet, in which case it will start listening to
   1765             // preview area size change later in the initialization.
   1766             mAppController.addPreviewAreaSizeChangedListener(mFocusManager);
   1767         }
   1768 
   1769         if (mPreviewing) {
   1770             mOnResumeTime = SystemClock.uptimeMillis();
   1771             mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100);
   1772         }
   1773         getServices().getMemoryManager().addListener(this);
   1774     }
   1775 
   1776     @Override
   1777     public void pause() {
   1778         mPaused = true;
   1779 
   1780         mAppController.getOrientationManager().removeOnOrientationChangeListener(this);
   1781 
   1782         if (mFocusManager != null) {
   1783             // If camera is not open when resume is called, focus manager will not
   1784             // be initialized yet, in which case it will start listening to
   1785             // preview area size change later in the initialization.
   1786             mAppController.removePreviewAreaSizeChangedListener(mFocusManager);
   1787             mFocusManager.removeMessages();
   1788         }
   1789         if (mMediaRecorderRecording) {
   1790             // Camera will be released in onStopVideoRecording.
   1791             onStopVideoRecording();
   1792         } else {
   1793             stopPreview();
   1794             closeCamera();
   1795             releaseMediaRecorder();
   1796         }
   1797 
   1798         closeVideoFileDescriptor();
   1799 
   1800         if (mReceiver != null) {
   1801             mActivity.unregisterReceiver(mReceiver);
   1802             mReceiver = null;
   1803         }
   1804 
   1805         mHandler.removeMessages(MSG_CHECK_DISPLAY_ROTATION);
   1806         mHandler.removeMessages(MSG_SWITCH_CAMERA);
   1807         mHandler.removeMessages(MSG_SWITCH_CAMERA_START_ANIMATION);
   1808         mPendingSwitchCameraId = -1;
   1809         mSwitchingCamera = false;
   1810         mPreferenceRead = false;
   1811         getServices().getMemoryManager().removeListener(this);
   1812         mUI.onPause();
   1813     }
   1814 
   1815     @Override
   1816     public void destroy() {
   1817 
   1818     }
   1819 
   1820     @Override
   1821     public void onLayoutOrientationChanged(boolean isLandscape) {
   1822         setDisplayOrientation();
   1823     }
   1824 
   1825     // TODO: integrate this into the SettingsManager listeners.
   1826     public void onSharedPreferenceChanged() {
   1827 
   1828     }
   1829 
   1830     private void switchCamera() {
   1831         if (mPaused)  {
   1832             return;
   1833         }
   1834         SettingsManager settingsManager = mActivity.getSettingsManager();
   1835 
   1836         Log.d(TAG, "Start to switch camera.");
   1837         mCameraId = mPendingSwitchCameraId;
   1838         mPendingSwitchCameraId = -1;
   1839         settingsManager.set(mAppController.getModuleScope(),
   1840                             Keys.KEY_CAMERA_ID, mCameraId);
   1841 
   1842         if (mFocusManager != null) {
   1843             mFocusManager.removeMessages();
   1844         }
   1845         closeCamera();
   1846         requestCamera(mCameraId);
   1847 
   1848         mMirror = isCameraFrontFacing();
   1849         if (mFocusManager != null) {
   1850             mFocusManager.setMirror(mMirror);
   1851         }
   1852 
   1853         // From onResume
   1854         mZoomValue = 1.0f;
   1855         mUI.setOrientationIndicator(0, false);
   1856 
   1857         // Start switch camera animation. Post a message because
   1858         // onFrameAvailable from the old camera may already exist.
   1859         mHandler.sendEmptyMessage(MSG_SWITCH_CAMERA_START_ANIMATION);
   1860         mUI.updateOnScreenIndicators(mCameraSettings);
   1861     }
   1862 
   1863     private void initializeVideoSnapshot() {
   1864         if (mCameraSettings == null) {
   1865             return;
   1866         }
   1867     }
   1868 
   1869     void showVideoSnapshotUI(boolean enabled) {
   1870         if (mCameraSettings == null) {
   1871             return;
   1872         }
   1873         if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT) &&
   1874                 !mIsVideoCaptureIntent) {
   1875             if (enabled) {
   1876                 mAppController.startFlashAnimation(false);
   1877             } else {
   1878                 mUI.showPreviewBorder(enabled);
   1879             }
   1880             mAppController.setShutterEnabled(!enabled);
   1881         }
   1882     }
   1883 
   1884     /**
   1885      * Used to update the flash mode. Video mode can turn on the flash as torch
   1886      * mode, which we would like to turn on and off when we switching in and
   1887      * out to the preview.
   1888      *
   1889      * @param enable Whether torch mode can be enabled.
   1890      */
   1891     private void enableTorchMode(boolean enable) {
   1892         if (mCameraSettings.getCurrentFlashMode() == null) {
   1893             return;
   1894         }
   1895 
   1896         SettingsManager settingsManager = mActivity.getSettingsManager();
   1897 
   1898         CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier();
   1899         CameraCapabilities.FlashMode flashMode;
   1900         if (enable) {
   1901             flashMode = stringifier
   1902                 .flashModeFromString(settingsManager.getString(mAppController.getCameraScope(),
   1903                                                                Keys.KEY_VIDEOCAMERA_FLASH_MODE));
   1904         } else {
   1905             flashMode = CameraCapabilities.FlashMode.OFF;
   1906         }
   1907         if (mCameraCapabilities.supports(flashMode)) {
   1908             mCameraSettings.setFlashMode(flashMode);
   1909         }
   1910         /* TODO: Find out how to deal with the following code piece:
   1911         else {
   1912             flashMode = mCameraSettings.getCurrentFlashMode();
   1913             if (flashMode == null) {
   1914                 flashMode = mActivity.getString(
   1915                         R.string.pref_camera_flashmode_no_flash);
   1916                 mParameters.setFlashMode(flashMode);
   1917             }
   1918         }*/
   1919         if (mCameraDevice != null) {
   1920             mCameraDevice.applySettings(mCameraSettings);
   1921         }
   1922         mUI.updateOnScreenIndicators(mCameraSettings);
   1923     }
   1924 
   1925     @Override
   1926     public void onPreviewVisibilityChanged(int visibility) {
   1927         if (mPreviewing) {
   1928             enableTorchMode(visibility == ModuleController.VISIBILITY_VISIBLE);
   1929         }
   1930     }
   1931 
   1932     private final class JpegPictureCallback implements CameraPictureCallback {
   1933         Location mLocation;
   1934 
   1935         public JpegPictureCallback(Location loc) {
   1936             mLocation = loc;
   1937         }
   1938 
   1939         @Override
   1940         public void onPictureTaken(byte [] jpegData, CameraProxy camera) {
   1941             Log.i(TAG, "Video snapshot taken.");
   1942             mSnapshotInProgress = false;
   1943             showVideoSnapshotUI(false);
   1944             storeImage(jpegData, mLocation);
   1945         }
   1946     }
   1947 
   1948     private void storeImage(final byte[] data, Location loc) {
   1949         long dateTaken = System.currentTimeMillis();
   1950         String title = CameraUtil.instance().createJpegName(dateTaken);
   1951         ExifInterface exif = Exif.getExif(data);
   1952         int orientation = Exif.getOrientation(exif);
   1953 
   1954         String flashSetting = mActivity.getSettingsManager()
   1955             .getString(mAppController.getCameraScope(), Keys.KEY_VIDEOCAMERA_FLASH_MODE);
   1956         Boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager());
   1957         UsageStatistics.instance().photoCaptureDoneEvent(
   1958                 eventprotos.NavigationChange.Mode.VIDEO_STILL, title + ".jpeg", exif,
   1959                 isCameraFrontFacing(), false, currentZoomValue(), flashSetting, gridLinesOn,
   1960                 null, null, null, null, null, null, null);
   1961 
   1962         getServices().getMediaSaver().addImage(data, title, dateTaken, loc, orientation, exif,
   1963                 mOnPhotoSavedListener);
   1964     }
   1965 
   1966     private String convertOutputFormatToMimeType(int outputFileFormat) {
   1967         if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
   1968             return "video/mp4";
   1969         }
   1970         return "video/3gpp";
   1971     }
   1972 
   1973     private String convertOutputFormatToFileExt(int outputFileFormat) {
   1974         if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
   1975             return ".mp4";
   1976         }
   1977         return ".3gp";
   1978     }
   1979 
   1980     private void closeVideoFileDescriptor() {
   1981         if (mVideoFileDescriptor != null) {
   1982             try {
   1983                 mVideoFileDescriptor.close();
   1984             } catch (IOException e) {
   1985                 Log.e(TAG, "Fail to close fd", e);
   1986             }
   1987             mVideoFileDescriptor = null;
   1988         }
   1989     }
   1990 
   1991     @Override
   1992     public void onPreviewUIReady() {
   1993         startPreview();
   1994     }
   1995 
   1996     @Override
   1997     public void onPreviewUIDestroyed() {
   1998         stopPreview();
   1999     }
   2000 
   2001     private void requestCamera(int id) {
   2002         mActivity.getCameraProvider().requestCamera(id);
   2003     }
   2004 
   2005     @Override
   2006     public void onMemoryStateChanged(int state) {
   2007         mAppController.setShutterEnabled(state == MemoryManager.STATE_OK);
   2008     }
   2009 
   2010     @Override
   2011     public void onLowMemory() {
   2012         // Not much we can do in the video module.
   2013     }
   2014 
   2015     /***********************FocusOverlayManager Listener****************************/
   2016     @Override
   2017     public void autoFocus() {
   2018         if (mCameraDevice != null) {
   2019             mCameraDevice.autoFocus(mHandler, mAutoFocusCallback);
   2020         }
   2021     }
   2022 
   2023     @Override
   2024     public void cancelAutoFocus() {
   2025         if (mCameraDevice != null) {
   2026             mCameraDevice.cancelAutoFocus();
   2027             setFocusParameters();
   2028         }
   2029     }
   2030 
   2031     @Override
   2032     public boolean capture() {
   2033         return false;
   2034     }
   2035 
   2036     @Override
   2037     public void startFaceDetection() {
   2038 
   2039     }
   2040 
   2041     @Override
   2042     public void stopFaceDetection() {
   2043 
   2044     }
   2045 
   2046     @Override
   2047     public void setFocusParameters() {
   2048         if (mCameraDevice != null) {
   2049             updateFocusParameters();
   2050             mCameraDevice.applySettings(mCameraSettings);
   2051         }
   2052     }
   2053 }
   2054