OSDN Git Service

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