OSDN Git Service

Fix crash in AOSP Camera app when recording video
[android-x86/packages-apps-Camera2.git] / src / com / android / camera / VideoModule.java
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         try {
1329             mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
1330         } catch (SecurityException e) {
1331             Log.e(TAG, "Error: " + e);
1332         }
1333     }
1334
1335     private void restoreRingerMode() {
1336         // First check if ringer mode was changed during the recording. If not,
1337         // re-set the mode that was set before video recording started.
1338         if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
1339             // Set the original ringer mode back.
1340             try {
1341                 mAudioManager.setRingerMode(mOriginalRingerMode);
1342             } catch (SecurityException e) {
1343                 Log.e(TAG, "Error: " + e);
1344             }
1345         }
1346     }
1347
1348     // For testing.
1349     public boolean isRecording() {
1350         return mMediaRecorderRecording;
1351     }
1352
1353     private void startVideoRecording() {
1354         Log.i(TAG, "startVideoRecording: " + Thread.currentThread());
1355         mUI.cancelAnimations();
1356         mUI.setSwipingEnabled(false);
1357         mUI.hidePassiveFocusIndicator();
1358         mAppController.getCameraAppUI().hideCaptureIndicator();
1359         mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(true);
1360
1361         mActivity.updateStorageSpaceAndHint(new CameraActivity.OnStorageUpdateDoneListener() {
1362             @Override
1363             public void onStorageUpdateDone(long bytes) {
1364                 if (bytes <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
1365                     Log.w(TAG, "Storage issue, ignore the start request");
1366                 } else {
1367                     if (mCameraDevice == null) {
1368                         Log.v(TAG, "in storage callback after camera closed");
1369                         return;
1370                     }
1371                     if (mPaused == true) {
1372                         Log.v(TAG, "in storage callback after module paused");
1373                         return;
1374                     }
1375
1376                     // Monkey is so fast so it could trigger startVideoRecording twice. To prevent
1377                     // app crash (b/17313985), do nothing here for the second storage-checking
1378                     // callback because recording is already started.
1379                     if (mMediaRecorderRecording) {
1380                         Log.v(TAG, "in storage callback after recording started");
1381                         return;
1382                     }
1383
1384                     mCurrentVideoUri = null;
1385
1386                     initializeRecorder();
1387                     if (mMediaRecorder == null) {
1388                         Log.e(TAG, "Fail to initialize media recorder");
1389                         return;
1390                     }
1391
1392                     try {
1393                         mMediaRecorder.start(); // Recording is now started
1394                     } catch (RuntimeException e) {
1395                         Log.e(TAG, "Could not start media recorder. ", e);
1396                         mAppController.getFatalErrorHandler().onGenericCameraAccessFailure();
1397                         releaseMediaRecorder();
1398                         // If start fails, frameworks will not lock the camera for us.
1399                         mCameraDevice.lock();
1400                         return;
1401                     }
1402                     // Make sure we stop playing sounds and disable the
1403                     // vibrations during video recording. Post delayed to avoid
1404                     // silencing the recording start sound.
1405                     mHandler.postDelayed(new Runnable() {
1406                         @Override
1407                         public void run() {
1408                             silenceSoundsAndVibrations();
1409                         }
1410                     }, 250);
1411
1412                     mAppController.getCameraAppUI().setSwipeEnabled(false);
1413
1414                     // The parameters might have been altered by MediaRecorder already.
1415                     // We need to force mCameraDevice to refresh before getting it.
1416                     mCameraDevice.refreshSettings();
1417                     // The parameters may have been changed by MediaRecorder upon starting
1418                     // recording. We need to alter the parameters if we support camcorder
1419                     // zoom. To reduce latency when setting the parameters during zoom, we
1420                     // update the settings here once.
1421                     mCameraSettings = mCameraDevice.getSettings();
1422
1423                     mMediaRecorderRecording = true;
1424                     mActivity.lockOrientation();
1425                     mRecordingStartTime = SystemClock.uptimeMillis();
1426
1427                     // A special case of mode options closing: during capture it should
1428                     // not be possible to change mode state.
1429                     mAppController.getCameraAppUI().hideModeOptions();
1430                     mAppController.getCameraAppUI().animateBottomBarToVideoStop(R.drawable.ic_stop);
1431                     mUI.showRecordingUI(true);
1432
1433                     setFocusParameters();
1434
1435                     updateRecordingTime();
1436                     mActivity.enableKeepScreenOn(true);
1437                 }
1438             }
1439         });
1440     }
1441
1442     private Bitmap getVideoThumbnail() {
1443         Bitmap bitmap = null;
1444         if (mVideoFileDescriptor != null) {
1445             bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
1446                     mDesiredPreviewWidth);
1447         } else if (mCurrentVideoUri != null) {
1448             try {
1449                 mVideoFileDescriptor = mContentResolver.openFileDescriptor(mCurrentVideoUri, "r");
1450                 bitmap = Thumbnail.createVideoThumbnailBitmap(
1451                         mVideoFileDescriptor.getFileDescriptor(), mDesiredPreviewWidth);
1452             } catch (java.io.FileNotFoundException ex) {
1453                 // invalid uri
1454                 Log.e(TAG, ex.toString());
1455             }
1456         }
1457
1458         if (bitmap != null) {
1459             // MetadataRetriever already rotates the thumbnail. We should rotate
1460             // it to match the UI orientation (and mirror if it is front-facing camera).
1461             bitmap = CameraUtil.rotateAndMirror(bitmap, 0, isCameraFrontFacing());
1462         }
1463         return bitmap;
1464     }
1465
1466     private void showCaptureResult() {
1467         mIsInReviewMode = true;
1468         Bitmap bitmap = getVideoThumbnail();
1469         if (bitmap != null) {
1470             mUI.showReviewImage(bitmap);
1471         }
1472         mUI.showReviewControls();
1473     }
1474
1475     private boolean stopVideoRecording() {
1476         // Do nothing if camera device is still capturing photo. Monkey test can trigger app crashes
1477         // (b/17313985) without this check. Crash could also be reproduced by continuously tapping
1478         // on shutter button and preview with two fingers.
1479         if (mSnapshotInProgress) {
1480             Log.v(TAG, "Skip stopVideoRecording since snapshot in progress");
1481             return true;
1482         }
1483         Log.v(TAG, "stopVideoRecording");
1484
1485         // Re-enable sound as early as possible to avoid interfering with stop
1486         // recording sound.
1487         restoreRingerMode();
1488
1489         mUI.setSwipingEnabled(true);
1490         mUI.showPassiveFocusIndicator();
1491         mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(false);
1492
1493         boolean fail = false;
1494         if (mMediaRecorderRecording) {
1495             boolean shouldAddToMediaStoreNow = false;
1496
1497             try {
1498                 mMediaRecorder.setOnErrorListener(null);
1499                 mMediaRecorder.setOnInfoListener(null);
1500                 mMediaRecorder.stop();
1501                 shouldAddToMediaStoreNow = true;
1502                 mCurrentVideoFilename = mVideoFilename;
1503                 Log.v(TAG, "stopVideoRecording: current video filename: " + mCurrentVideoFilename);
1504             } catch (RuntimeException e) {
1505                 Log.e(TAG, "stop fail",  e);
1506                 if (mVideoFilename != null) {
1507                     deleteVideoFile(mVideoFilename);
1508                 }
1509                 fail = true;
1510             }
1511             mMediaRecorderRecording = false;
1512             mActivity.unlockOrientation();
1513
1514             // If the activity is paused, this means activity is interrupted
1515             // during recording. Release the camera as soon as possible because
1516             // face unlock or other applications may need to use the camera.
1517             if (mPaused) {
1518                 // b/16300704: Monkey is fast so it could pause the module while recording.
1519                 // stopPreview should definitely be called before switching off.
1520                 stopPreview();
1521                 closeCamera();
1522             }
1523
1524             mUI.showRecordingUI(false);
1525             // The orientation was fixed during video recording. Now make it
1526             // reflect the device orientation as video recording is stopped.
1527             mUI.setOrientationIndicator(0, true);
1528             mActivity.enableKeepScreenOn(false);
1529             if (shouldAddToMediaStoreNow && !fail) {
1530                 if (mVideoFileDescriptor == null) {
1531                     saveVideo();
1532                 } else if (mIsVideoCaptureIntent) {
1533                     // if no file save is needed, we can show the post capture UI now
1534                     showCaptureResult();
1535                 }
1536             }
1537         }
1538         // release media recorder
1539         releaseMediaRecorder();
1540
1541         mAppController.getCameraAppUI().showModeOptions();
1542         mAppController.getCameraAppUI().animateBottomBarToFullSize(mShutterIconId);
1543         if (!mPaused && mCameraDevice != null) {
1544             setFocusParameters();
1545             mCameraDevice.lock();
1546             if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
1547                 stopPreview();
1548                 // Switch back to use SurfaceTexture for preview.
1549                 startPreview();
1550             }
1551             // Update the parameters here because the parameters might have been altered
1552             // by MediaRecorder.
1553             mCameraSettings = mCameraDevice.getSettings();
1554         }
1555
1556         // Check this in advance of each shot so we don't add to shutter
1557         // latency. It's true that someone else could write to the SD card
1558         // in the mean time and fill it, but that could have happened
1559         // between the shutter press and saving the file too.
1560         mActivity.updateStorageSpaceAndHint(null);
1561
1562         return fail;
1563     }
1564
1565     private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
1566         long seconds = milliSeconds / 1000; // round down to compute seconds
1567         long minutes = seconds / 60;
1568         long hours = minutes / 60;
1569         long remainderMinutes = minutes - (hours * 60);
1570         long remainderSeconds = seconds - (minutes * 60);
1571
1572         StringBuilder timeStringBuilder = new StringBuilder();
1573
1574         // Hours
1575         if (hours > 0) {
1576             if (hours < 10) {
1577                 timeStringBuilder.append('0');
1578             }
1579             timeStringBuilder.append(hours);
1580
1581             timeStringBuilder.append(':');
1582         }
1583
1584         // Minutes
1585         if (remainderMinutes < 10) {
1586             timeStringBuilder.append('0');
1587         }
1588         timeStringBuilder.append(remainderMinutes);
1589         timeStringBuilder.append(':');
1590
1591         // Seconds
1592         if (remainderSeconds < 10) {
1593             timeStringBuilder.append('0');
1594         }
1595         timeStringBuilder.append(remainderSeconds);
1596
1597         // Centi seconds
1598         if (displayCentiSeconds) {
1599             timeStringBuilder.append('.');
1600             long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
1601             if (remainderCentiSeconds < 10) {
1602                 timeStringBuilder.append('0');
1603             }
1604             timeStringBuilder.append(remainderCentiSeconds);
1605         }
1606
1607         return timeStringBuilder.toString();
1608     }
1609
1610     private void updateRecordingTime() {
1611         if (!mMediaRecorderRecording) {
1612             return;
1613         }
1614         long now = SystemClock.uptimeMillis();
1615         long delta = now - mRecordingStartTime;
1616
1617         // Starting a minute before reaching the max duration
1618         // limit, we'll countdown the remaining time instead.
1619         boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
1620                 && delta >= mMaxVideoDurationInMs - 60000);
1621
1622         long deltaAdjusted = delta;
1623         if (countdownRemainingTime) {
1624             deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
1625         }
1626         String text;
1627
1628         long targetNextUpdateDelay;
1629
1630         text = millisecondToTimeString(deltaAdjusted, false);
1631         targetNextUpdateDelay = 1000;
1632
1633         mUI.setRecordingTime(text);
1634
1635         if (mRecordingTimeCountsDown != countdownRemainingTime) {
1636             // Avoid setting the color on every update, do it only
1637             // when it needs changing.
1638             mRecordingTimeCountsDown = countdownRemainingTime;
1639
1640             int color = mActivity.getResources().getColor(R.color.recording_time_remaining_text);
1641
1642             mUI.setRecordingTimeTextColor(color);
1643         }
1644
1645         long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
1646         mHandler.sendEmptyMessageDelayed(MSG_UPDATE_RECORD_TIME, actualNextUpdateDelay);
1647     }
1648
1649     private static boolean isSupported(String value, List<String> supported) {
1650         return supported == null ? false : supported.indexOf(value) >= 0;
1651     }
1652
1653     @SuppressWarnings("deprecation")
1654     private void setCameraParameters() {
1655         SettingsManager settingsManager = mActivity.getSettingsManager();
1656
1657         // Update Desired Preview size in case video camera resolution has changed.
1658         updateDesiredPreviewSize();
1659
1660         Size previewSize = new Size(mDesiredPreviewWidth, mDesiredPreviewHeight);
1661         mCameraSettings.setPreviewSize(previewSize.toPortabilitySize());
1662         // This is required for Samsung SGH-I337 and probably other Samsung S4 versions
1663         if (Build.BRAND.toLowerCase().contains("samsung")) {
1664             mCameraSettings.setSetting("video-size",
1665                     mProfile.videoFrameWidth + "x" + mProfile.videoFrameHeight);
1666         }
1667         int[] fpsRange =
1668                 CameraUtil.getMaxPreviewFpsRange(mCameraCapabilities.getSupportedPreviewFpsRange());
1669         if (fpsRange.length > 0) {
1670             mCameraSettings.setPreviewFpsRange(fpsRange[0], fpsRange[1]);
1671         } else {
1672             mCameraSettings.setPreviewFrameRate(mProfile.videoFrameRate);
1673         }
1674
1675         enableTorchMode(Keys.isCameraBackFacing(settingsManager, mAppController.getModuleScope()));
1676
1677         // Set zoom.
1678         if (mCameraCapabilities.supports(CameraCapabilities.Feature.ZOOM)) {
1679             mCameraSettings.setZoomRatio(mZoomValue);
1680         }
1681         updateFocusParameters();
1682
1683         mCameraSettings.setRecordingHintEnabled(true);
1684
1685         if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_STABILIZATION)) {
1686             mCameraSettings.setVideoStabilization(true);
1687         }
1688
1689         // Set picture size.
1690         // The logic here is different from the logic in still-mode camera.
1691         // There we determine the preview size based on the picture size, but
1692         // here we determine the picture size based on the preview size.
1693         List<Size> supported = Size.convert(mCameraCapabilities.getSupportedPhotoSizes());
1694         Size optimalSize = CameraUtil.getOptimalVideoSnapshotPictureSize(supported,
1695                 mDesiredPreviewWidth, mDesiredPreviewHeight);
1696         Size original = new Size(mCameraSettings.getCurrentPhotoSize());
1697         if (!original.equals(optimalSize)) {
1698             mCameraSettings.setPhotoSize(optimalSize.toPortabilitySize());
1699         }
1700         Log.d(TAG, "Video snapshot size is " + optimalSize);
1701
1702         // Set JPEG quality.
1703         int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1704                 CameraProfile.QUALITY_HIGH);
1705         mCameraSettings.setPhotoJpegCompressionQuality(jpegQuality);
1706
1707         if (mCameraDevice != null) {
1708             mCameraDevice.applySettings(mCameraSettings);
1709             // Nexus 5 through KitKat 4.4.2 requires a second call to
1710             // .setParameters() for frame rate settings to take effect.
1711             mCameraDevice.applySettings(mCameraSettings);
1712         }
1713
1714         // Update UI based on the new parameters.
1715         mUI.updateOnScreenIndicators(mCameraSettings);
1716     }
1717
1718     private void updateFocusParameters() {
1719         // Set continuous autofocus. During recording, we use "continuous-video"
1720         // auto focus mode to ensure smooth focusing. Whereas during preview (i.e.
1721         // before recording starts) we use "continuous-picture" auto focus mode
1722         // for faster but slightly jittery focusing.
1723         Set<CameraCapabilities.FocusMode> supportedFocus = mCameraCapabilities
1724                 .getSupportedFocusModes();
1725         if (mMediaRecorderRecording) {
1726             if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO)) {
1727                 mCameraSettings.setFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
1728                 mFocusManager.overrideFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
1729             } else {
1730                 mFocusManager.overrideFocusMode(null);
1731             }
1732         } else {
1733             // FIXME(b/16984793): This is broken. For some reasons, CONTINUOUS_PICTURE is not on
1734             // when preview starts.
1735             mFocusManager.overrideFocusMode(null);
1736             if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_PICTURE)) {
1737                 mCameraSettings.setFocusMode(
1738                         mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode()));
1739                 if (mFocusAreaSupported) {
1740                     mCameraSettings.setFocusAreas(mFocusManager.getFocusAreas());
1741                 }
1742             }
1743         }
1744         updateAutoFocusMoveCallback();
1745     }
1746
1747     @Override
1748     public void resume() {
1749         if (isVideoCaptureIntent()) {
1750             mDontResetIntentUiOnResume = mPaused;
1751         }
1752
1753         mPaused = false;
1754         installIntentFilter();
1755         mAppController.setShutterEnabled(false);
1756         mZoomValue = 1.0f;
1757
1758         OrientationManager orientationManager = mAppController.getOrientationManager();
1759         orientationManager.addOnOrientationChangeListener(this);
1760         mUI.onOrientationChanged(orientationManager, orientationManager.getDeviceOrientation());
1761
1762         showVideoSnapshotUI(false);
1763
1764         if (!mPreviewing) {
1765             requestCamera(mCameraId);
1766         } else {
1767             // preview already started
1768             mAppController.setShutterEnabled(true);
1769         }
1770
1771         if (mFocusManager != null) {
1772             // If camera is not open when resume is called, focus manager will not
1773             // be initialized yet, in which case it will start listening to
1774             // preview area size change later in the initialization.
1775             mAppController.addPreviewAreaSizeChangedListener(mFocusManager);
1776         }
1777
1778         if (mPreviewing) {
1779             mOnResumeTime = SystemClock.uptimeMillis();
1780             mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100);
1781         }
1782         getServices().getMemoryManager().addListener(this);
1783     }
1784
1785     @Override
1786     public void pause() {
1787         mPaused = true;
1788
1789         mAppController.getOrientationManager().removeOnOrientationChangeListener(this);
1790
1791         if (mFocusManager != null) {
1792             // If camera is not open when resume is called, focus manager will not
1793             // be initialized yet, in which case it will start listening to
1794             // preview area size change later in the initialization.
1795             mAppController.removePreviewAreaSizeChangedListener(mFocusManager);
1796             mFocusManager.removeMessages();
1797         }
1798         if (mMediaRecorderRecording) {
1799             // Camera will be released in onStopVideoRecording.
1800             onStopVideoRecording();
1801         } else {
1802             stopPreview();
1803             closeCamera();
1804             releaseMediaRecorder();
1805         }
1806
1807         closeVideoFileDescriptor();
1808
1809         if (mReceiver != null) {
1810             mActivity.unregisterReceiver(mReceiver);
1811             mReceiver = null;
1812         }
1813
1814         mHandler.removeMessages(MSG_CHECK_DISPLAY_ROTATION);
1815         mHandler.removeMessages(MSG_SWITCH_CAMERA);
1816         mHandler.removeMessages(MSG_SWITCH_CAMERA_START_ANIMATION);
1817         mPendingSwitchCameraId = -1;
1818         mSwitchingCamera = false;
1819         mPreferenceRead = false;
1820         getServices().getMemoryManager().removeListener(this);
1821         mUI.onPause();
1822     }
1823
1824     @Override
1825     public void destroy() {
1826
1827     }
1828
1829     @Override
1830     public void onLayoutOrientationChanged(boolean isLandscape) {
1831         setDisplayOrientation();
1832     }
1833
1834     // TODO: integrate this into the SettingsManager listeners.
1835     public void onSharedPreferenceChanged() {
1836
1837     }
1838
1839     private void switchCamera() {
1840         if (mPaused)  {
1841             return;
1842         }
1843         SettingsManager settingsManager = mActivity.getSettingsManager();
1844
1845         Log.d(TAG, "Start to switch camera.");
1846         mCameraId = mPendingSwitchCameraId;
1847         mPendingSwitchCameraId = -1;
1848         settingsManager.set(mAppController.getModuleScope(),
1849                             Keys.KEY_CAMERA_ID, mCameraId);
1850
1851         if (mFocusManager != null) {
1852             mFocusManager.removeMessages();
1853         }
1854         closeCamera();
1855         requestCamera(mCameraId);
1856
1857         mMirror = isCameraFrontFacing();
1858         if (mFocusManager != null) {
1859             mFocusManager.setMirror(mMirror);
1860         }
1861
1862         // From onResume
1863         mZoomValue = 1.0f;
1864         mUI.setOrientationIndicator(0, false);
1865
1866         // Start switch camera animation. Post a message because
1867         // onFrameAvailable from the old camera may already exist.
1868         mHandler.sendEmptyMessage(MSG_SWITCH_CAMERA_START_ANIMATION);
1869         mUI.updateOnScreenIndicators(mCameraSettings);
1870     }
1871
1872     private void initializeVideoSnapshot() {
1873         if (mCameraSettings == null) {
1874             return;
1875         }
1876     }
1877
1878     void showVideoSnapshotUI(boolean enabled) {
1879         if (mCameraSettings == null) {
1880             return;
1881         }
1882         if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT) &&
1883                 !mIsVideoCaptureIntent) {
1884             if (enabled) {
1885                 mAppController.startFlashAnimation(false);
1886             } else {
1887                 mUI.showPreviewBorder(enabled);
1888             }
1889             mAppController.setShutterEnabled(!enabled);
1890         }
1891     }
1892
1893     /**
1894      * Used to update the flash mode. Video mode can turn on the flash as torch
1895      * mode, which we would like to turn on and off when we switching in and
1896      * out to the preview.
1897      *
1898      * @param enable Whether torch mode can be enabled.
1899      */
1900     private void enableTorchMode(boolean enable) {
1901         if (mCameraSettings.getCurrentFlashMode() == null) {
1902             return;
1903         }
1904
1905         SettingsManager settingsManager = mActivity.getSettingsManager();
1906
1907         CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier();
1908         CameraCapabilities.FlashMode flashMode;
1909         if (enable) {
1910             flashMode = stringifier
1911                 .flashModeFromString(settingsManager.getString(mAppController.getCameraScope(),
1912                                                                Keys.KEY_VIDEOCAMERA_FLASH_MODE));
1913         } else {
1914             flashMode = CameraCapabilities.FlashMode.OFF;
1915         }
1916         if (mCameraCapabilities.supports(flashMode)) {
1917             mCameraSettings.setFlashMode(flashMode);
1918         }
1919         /* TODO: Find out how to deal with the following code piece:
1920         else {
1921             flashMode = mCameraSettings.getCurrentFlashMode();
1922             if (flashMode == null) {
1923                 flashMode = mActivity.getString(
1924                         R.string.pref_camera_flashmode_no_flash);
1925                 mParameters.setFlashMode(flashMode);
1926             }
1927         }*/
1928         if (mCameraDevice != null) {
1929             mCameraDevice.applySettings(mCameraSettings);
1930         }
1931         mUI.updateOnScreenIndicators(mCameraSettings);
1932     }
1933
1934     @Override
1935     public void onPreviewVisibilityChanged(int visibility) {
1936         if (mPreviewing) {
1937             enableTorchMode(visibility == ModuleController.VISIBILITY_VISIBLE);
1938         }
1939     }
1940
1941     private final class JpegPictureCallback implements CameraPictureCallback {
1942         Location mLocation;
1943
1944         public JpegPictureCallback(Location loc) {
1945             mLocation = loc;
1946         }
1947
1948         @Override
1949         public void onPictureTaken(byte [] jpegData, CameraProxy camera) {
1950             Log.i(TAG, "Video snapshot taken.");
1951             mSnapshotInProgress = false;
1952             showVideoSnapshotUI(false);
1953             storeImage(jpegData, mLocation);
1954         }
1955     }
1956
1957     private void storeImage(final byte[] data, Location loc) {
1958         long dateTaken = System.currentTimeMillis();
1959         String title = CameraUtil.instance().createJpegName(dateTaken);
1960         ExifInterface exif = Exif.getExif(data);
1961         int orientation = Exif.getOrientation(exif);
1962
1963         String flashSetting = mActivity.getSettingsManager()
1964             .getString(mAppController.getCameraScope(), Keys.KEY_VIDEOCAMERA_FLASH_MODE);
1965         Boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager());
1966         UsageStatistics.instance().photoCaptureDoneEvent(
1967                 eventprotos.NavigationChange.Mode.VIDEO_STILL, title + ".jpeg", exif,
1968                 isCameraFrontFacing(), false, currentZoomValue(), flashSetting, gridLinesOn,
1969                 null, null, null, null, null, null, null);
1970
1971         getServices().getMediaSaver().addImage(data, title, dateTaken, loc, orientation, exif,
1972                 mOnPhotoSavedListener);
1973     }
1974
1975     private String convertOutputFormatToMimeType(int outputFileFormat) {
1976         if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
1977             return "video/mp4";
1978         }
1979         return "video/3gpp";
1980     }
1981
1982     private String convertOutputFormatToFileExt(int outputFileFormat) {
1983         if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
1984             return ".mp4";
1985         }
1986         return ".3gp";
1987     }
1988
1989     private void closeVideoFileDescriptor() {
1990         if (mVideoFileDescriptor != null) {
1991             try {
1992                 mVideoFileDescriptor.close();
1993             } catch (IOException e) {
1994                 Log.e(TAG, "Fail to close fd", e);
1995             }
1996             mVideoFileDescriptor = null;
1997         }
1998     }
1999
2000     @Override
2001     public void onPreviewUIReady() {
2002         startPreview();
2003     }
2004
2005     @Override
2006     public void onPreviewUIDestroyed() {
2007         stopPreview();
2008     }
2009
2010     private void requestCamera(int id) {
2011         mActivity.getCameraProvider().requestCamera(id);
2012     }
2013
2014     @Override
2015     public void onMemoryStateChanged(int state) {
2016         mAppController.setShutterEnabled(state == MemoryManager.STATE_OK);
2017     }
2018
2019     @Override
2020     public void onLowMemory() {
2021         // Not much we can do in the video module.
2022     }
2023
2024     /***********************FocusOverlayManager Listener****************************/
2025     @Override
2026     public void autoFocus() {
2027         if (mCameraDevice != null) {
2028             mCameraDevice.autoFocus(mHandler, mAutoFocusCallback);
2029         }
2030     }
2031
2032     @Override
2033     public void cancelAutoFocus() {
2034         if (mCameraDevice != null) {
2035             mCameraDevice.cancelAutoFocus();
2036             setFocusParameters();
2037         }
2038     }
2039
2040     @Override
2041     public boolean capture() {
2042         return false;
2043     }
2044
2045     @Override
2046     public void startFaceDetection() {
2047
2048     }
2049
2050     @Override
2051     public void stopFaceDetection() {
2052
2053     }
2054
2055     @Override
2056     public void setFocusParameters() {
2057         if (mCameraDevice != null) {
2058             updateFocusParameters();
2059             mCameraDevice.applySettings(mCameraSettings);
2060         }
2061     }
2062 }