VideoModule.java revision fdb79c492940d46b27702b0be71903f99af7e34f
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera;
18
19import android.annotation.TargetApi;
20import android.app.Activity;
21import android.content.ActivityNotFoundException;
22import android.content.BroadcastReceiver;
23import android.content.ContentResolver;
24import android.content.ContentValues;
25import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.SharedPreferences.Editor;
29import android.content.res.Configuration;
30import android.graphics.Bitmap;
31import android.hardware.Camera.CameraInfo;
32import android.hardware.Camera.Parameters;
33import android.hardware.Camera.PictureCallback;
34import android.hardware.Camera.Size;
35import android.location.Location;
36import android.media.CamcorderProfile;
37import android.media.CameraProfile;
38import android.media.MediaRecorder;
39import android.net.Uri;
40import android.os.Build;
41import android.os.Bundle;
42import android.os.Handler;
43import android.os.Message;
44import android.os.ParcelFileDescriptor;
45import android.os.SystemClock;
46import android.provider.MediaStore;
47import android.provider.MediaStore.Video;
48import android.util.Log;
49import android.view.Gravity;
50import android.view.KeyEvent;
51import android.view.LayoutInflater;
52import android.view.MotionEvent;
53import android.view.OrientationEventListener;
54import android.view.SurfaceHolder;
55import android.view.View;
56import android.view.View.OnClickListener;
57import android.view.ViewGroup;
58import android.view.WindowManager;
59import android.widget.FrameLayout;
60import android.widget.FrameLayout.LayoutParams;
61import android.widget.ImageView;
62import android.widget.LinearLayout;
63import android.widget.TextView;
64import android.widget.Toast;
65
66import com.android.camera.ui.AbstractSettingPopup;
67import com.android.camera.ui.CameraPicker;
68import com.android.camera.ui.PieRenderer;
69import com.android.camera.ui.PopupManager;
70import com.android.camera.ui.PreviewSurfaceView;
71import com.android.camera.ui.RenderOverlay;
72import com.android.camera.ui.Rotatable;
73import com.android.camera.ui.RotateImageView;
74import com.android.camera.ui.RotateLayout;
75import com.android.camera.ui.RotateTextToast;
76import com.android.camera.ui.TwoStateImageView;
77import com.android.camera.ui.ZoomControl;
78import com.android.gallery3d.common.ApiHelper;
79
80import java.io.File;
81import java.io.IOException;
82import java.text.SimpleDateFormat;
83import java.util.Date;
84import java.util.Iterator;
85import java.util.List;
86
87public class VideoModule implements CameraModule,
88    CameraPreference.OnPreferenceChangedListener,
89    ShutterButton.OnShutterButtonListener,
90    MediaRecorder.OnErrorListener,
91    MediaRecorder.OnInfoListener,
92    EffectsRecorder.EffectsListener,
93    PieRenderer.PieListener {
94
95    private static final String TAG = "CAM_VideoModule";
96
97    // We number the request code from 1000 to avoid collision with Gallery.
98    private static final int REQUEST_EFFECT_BACKDROPPER = 1000;
99
100    private static final int CHECK_DISPLAY_ROTATION = 3;
101    private static final int CLEAR_SCREEN_DELAY = 4;
102    private static final int UPDATE_RECORD_TIME = 5;
103    private static final int ENABLE_SHUTTER_BUTTON = 6;
104    private static final int SHOW_TAP_TO_SNAPSHOT_TOAST = 7;
105    private static final int SWITCH_CAMERA = 8;
106    private static final int SWITCH_CAMERA_START_ANIMATION = 9;
107    private static final int HIDE_SURFACE_VIEW = 10;
108
109    private static final int SCREEN_DELAY = 2 * 60 * 1000;
110
111    private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms
112
113    /**
114     * An unpublished intent flag requesting to start recording straight away
115     * and return as soon as recording is stopped.
116     * TODO: consider publishing by moving into MediaStore.
117     */
118    private static final String EXTRA_QUICK_CAPTURE =
119            "android.intent.extra.quickCapture";
120
121    private static final int MIN_THUMB_SIZE = 64;
122    // module fields
123    private CameraActivity mActivity;
124    private View mRootView;
125    private boolean mPaused;
126    private int mCameraId;
127    private Parameters mParameters;
128
129    private boolean mSnapshotInProgress = false;
130
131    private static final String EFFECT_BG_FROM_GALLERY = "gallery";
132
133    private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
134
135    private ComboPreferences mPreferences;
136    private PreferenceGroup mPreferenceGroup;
137
138    private PreviewFrameLayout mPreviewFrameLayout;
139    private boolean mSurfaceViewReady;
140    private SurfaceHolder.Callback mSurfaceViewCallback;
141    private PreviewSurfaceView mPreviewSurfaceView;
142    private CameraScreenNail.OnFrameDrawnListener mFrameDrawnListener;
143    private View mReviewControl;
144    private RotateDialogController mRotateDialog;
145
146    // An review image having same size as preview. It is displayed when
147    // recording is stopped in capture intent.
148    private ImageView mReviewImage;
149    private Rotatable mReviewCancelButton;
150    private Rotatable mReviewDoneButton;
151    private RotateImageView mReviewPlayButton;
152    private View mReviewRetakeButton;
153    private ShutterButton mShutterButton;
154    private TextView mRecordingTimeView;
155    private RotateLayout mBgLearningMessageRotater;
156    private View mBgLearningMessageFrame;
157    private LinearLayout mLabelsLinearLayout;
158
159    private boolean mIsVideoCaptureIntent;
160    private boolean mQuickCapture;
161
162    private MediaRecorder mMediaRecorder;
163    private EffectsRecorder mEffectsRecorder;
164    private boolean mEffectsDisplayResult;
165
166    private int mEffectType = EffectsRecorder.EFFECT_NONE;
167    private Object mEffectParameter = null;
168    private String mEffectUriFromGallery = null;
169    private String mPrefVideoEffectDefault;
170    private boolean mResetEffect = true;
171
172    private boolean mSwitchingCamera;
173    private boolean mMediaRecorderRecording = false;
174    private long mRecordingStartTime;
175    private boolean mRecordingTimeCountsDown = false;
176    private RotateLayout mRecordingTimeRect;
177    private long mOnResumeTime;
178    // The video file that the hardware camera is about to record into
179    // (or is recording into.)
180    private String mVideoFilename;
181    private ParcelFileDescriptor mVideoFileDescriptor;
182
183    // The video file that has already been recorded, and that is being
184    // examined by the user.
185    private String mCurrentVideoFilename;
186    private Uri mCurrentVideoUri;
187    private ContentValues mCurrentVideoValues;
188
189    private CamcorderProfile mProfile;
190
191    // The video duration limit. 0 menas no limit.
192    private int mMaxVideoDurationInMs;
193
194    // Time Lapse parameters.
195    private boolean mCaptureTimeLapse = false;
196    // Default 0. If it is larger than 0, the camcorder is in time lapse mode.
197    private int mTimeBetweenTimeLapseFrameCaptureMs = 0;
198    private View mTimeLapseLabel;
199
200    private int mDesiredPreviewWidth;
201    private int mDesiredPreviewHeight;
202
203    boolean mPreviewing = false; // True if preview is started.
204    // The display rotation in degrees. This is only valid when mPreviewing is
205    // true.
206    private int mDisplayRotation;
207    private int mCameraDisplayOrientation;
208
209    private ContentResolver mContentResolver;
210
211    private LocationManager mLocationManager;
212
213    private VideoNamer mVideoNamer;
214
215    private RenderOverlay mRenderOverlay;
216    private PieRenderer mPieRenderer;
217
218    private VideoController mVideoControl;
219    private AbstractSettingPopup mPopup;
220    private int mPendingSwitchCameraId;
221    private boolean mControlEnabled;
222
223
224    private final Handler mHandler = new MainHandler();
225
226    private MyOrientationEventListener mOrientationListener;
227    // The degrees of the device rotated clockwise from its natural orientation.
228    private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
229    // The orientation compensation for icons and thumbnails. Ex: if the value
230    // is 90, the UI components should be rotated 90 degrees counter-clockwise.
231    private int mOrientationCompensation = 0;
232    // The orientation compensation when we start recording.
233    private int mOrientationCompensationAtRecordStart;
234
235    private int mZoomValue;  // The current zoom value.
236    private int mZoomMax;
237    private boolean mRestoreFlash;  // This is used to check if we need to restore the flash
238                                    // status when going back from gallery.
239
240    protected class CameraOpenThread extends Thread {
241        @Override
242        public void run() {
243            try {
244                mActivity.mCameraDevice = Util.openCamera(mActivity, mCameraId);
245                mParameters = mActivity.mCameraDevice.getParameters();
246            } catch (CameraHardwareException e) {
247                mActivity.mOpenCameraFail = true;
248            } catch (CameraDisabledException e) {
249                mActivity.mCameraDisabled = true;
250            }
251        }
252    }
253
254    // This Handler is used to post message back onto the main thread of the
255    // application
256    private class MainHandler extends Handler {
257        @Override
258        public void handleMessage(Message msg) {
259            switch (msg.what) {
260
261                case ENABLE_SHUTTER_BUTTON:
262                    mShutterButton.setEnabled(true);
263                    break;
264
265                case CLEAR_SCREEN_DELAY: {
266                    mActivity.getWindow().clearFlags(
267                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
268                    break;
269                }
270
271                case UPDATE_RECORD_TIME: {
272                    updateRecordingTime();
273                    break;
274                }
275
276                case CHECK_DISPLAY_ROTATION: {
277                    // Restart the preview if display rotation has changed.
278                    // Sometimes this happens when the device is held upside
279                    // down and camera app is opened. Rotation animation will
280                    // take some time and the rotation value we have got may be
281                    // wrong. Framework does not have a callback for this now.
282                    if ((Util.getDisplayRotation(mActivity) != mDisplayRotation)
283                            && !mMediaRecorderRecording && !mSwitchingCamera) {
284                        startPreview();
285                    }
286                    if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
287                        mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
288                    }
289                    break;
290                }
291
292                case SHOW_TAP_TO_SNAPSHOT_TOAST: {
293                    showTapToSnapshotToast();
294                    break;
295                }
296
297                case SWITCH_CAMERA: {
298                    switchCamera();
299                    break;
300                }
301
302                case SWITCH_CAMERA_START_ANIMATION: {
303                    ((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
304
305                    // Enable all camera controls.
306                    mSwitchingCamera = false;
307                    break;
308                }
309
310                case HIDE_SURFACE_VIEW: {
311                    mPreviewSurfaceView.setVisibility(View.GONE);
312                    break;
313                }
314
315                default:
316                    Log.v(TAG, "Unhandled message: " + msg.what);
317                    break;
318            }
319        }
320    }
321
322    private BroadcastReceiver mReceiver = null;
323
324    private class MyBroadcastReceiver extends BroadcastReceiver {
325        @Override
326        public void onReceive(Context context, Intent intent) {
327            String action = intent.getAction();
328            if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
329                stopVideoRecording();
330            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
331                Toast.makeText(mActivity,
332                        mActivity.getResources().getString(R.string.wait), Toast.LENGTH_LONG).show();
333            }
334        }
335    }
336
337    private String createName(long dateTaken) {
338        Date date = new Date(dateTaken);
339        SimpleDateFormat dateFormat = new SimpleDateFormat(
340                mActivity.getString(R.string.video_file_name_format));
341
342        return dateFormat.format(date);
343    }
344
345    private int getPreferredCameraId(ComboPreferences preferences) {
346        int intentCameraId = Util.getCameraFacingIntentExtras(mActivity);
347        if (intentCameraId != -1) {
348            // Testing purpose. Launch a specific camera through the intent
349            // extras.
350            return intentCameraId;
351        } else {
352            return CameraSettings.readPreferredCameraId(preferences);
353        }
354    }
355
356    private void initializeSurfaceView() {
357        mPreviewSurfaceView = (PreviewSurfaceView) mRootView.findViewById(R.id.preview_surface_view);
358        if (!ApiHelper.HAS_SURFACE_TEXTURE) {  // API level < 11
359            if (mSurfaceViewCallback == null) {
360                mSurfaceViewCallback = new SurfaceViewCallback();
361            }
362            mPreviewSurfaceView.getHolder().addCallback(mSurfaceViewCallback);
363            mPreviewSurfaceView.setVisibility(View.VISIBLE);
364        } else if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {  // API level < 16
365            if (mSurfaceViewCallback == null) {
366                mSurfaceViewCallback = new SurfaceViewCallback();
367                mFrameDrawnListener = new CameraScreenNail.OnFrameDrawnListener() {
368                    @Override
369                    public void onFrameDrawn(CameraScreenNail c) {
370                        mHandler.sendEmptyMessage(HIDE_SURFACE_VIEW);
371                    }
372                };
373            }
374            mPreviewSurfaceView.getHolder().addCallback(mSurfaceViewCallback);
375        }
376    }
377
378    private void initializeOverlay() {
379        mRenderOverlay = (RenderOverlay) mRootView.findViewById(R.id.render_overlay);
380        if (mPieRenderer == null) {
381            mPieRenderer = new PieRenderer(mActivity);
382            mRenderOverlay.addRenderer(mPieRenderer);
383            mVideoControl = new VideoController(mActivity, this, mPieRenderer);
384            mVideoControl.setListener(this);
385            mPieRenderer.setPieListener(this);
386        }
387    }
388
389    @Override
390    public void init(CameraActivity activity, View root, boolean reuseScreenNail) {
391        mActivity = activity;
392        mRootView = root;
393        mPreferences = new ComboPreferences(mActivity);
394        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
395        mCameraId = getPreferredCameraId(mPreferences);
396
397        mPreferences.setLocalId(mActivity, mCameraId);
398        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
399
400        mActivity.mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
401        mPrefVideoEffectDefault = mActivity.getString(R.string.pref_video_effect_default);
402        resetEffect();
403
404        /*
405         * To reduce startup time, we start the preview in another thread.
406         * We make sure the preview is started at the end of onCreate.
407         */
408        CameraOpenThread cameraOpenThread = new CameraOpenThread();
409        cameraOpenThread.start();
410
411        mContentResolver = mActivity.getContentResolver();
412
413        mActivity.getLayoutInflater().inflate(R.layout.video_module, (ViewGroup) mRootView);
414
415        // Surface texture is from camera screen nail and startPreview needs it.
416        // This must be done before startPreview.
417        mIsVideoCaptureIntent = isVideoCaptureIntent();
418        if (reuseScreenNail) {
419            mActivity.reuseCameraScreenNail(!mIsVideoCaptureIntent);
420        } else {
421            mActivity.createCameraScreenNail(!mIsVideoCaptureIntent);
422        }
423        initializeSurfaceView();
424
425        // Make sure camera device is opened.
426        try {
427            cameraOpenThread.join();
428            if (mActivity.mOpenCameraFail) {
429                Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera);
430                return;
431            } else if (mActivity.mCameraDisabled) {
432                Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
433                return;
434            }
435        } catch (InterruptedException ex) {
436            // ignore
437        }
438
439        Thread startPreviewThread = new Thread(new Runnable() {
440            @Override
441            public void run() {
442                readVideoPreferences();
443                startPreview();
444            }
445        });
446        startPreviewThread.start();
447
448        initializeOverlay();
449
450        initializeControlByIntent();
451        initializeMiscControls();
452
453        mRotateDialog = new RotateDialogController(mActivity, R.layout.rotate_dialog);
454        mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
455        mOrientationListener = new MyOrientationEventListener(mActivity);
456        mLocationManager = new LocationManager(mActivity, null);
457
458        // Make sure preview is started.
459        try {
460            startPreviewThread.join();
461            if (mActivity.mOpenCameraFail) {
462                Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera);
463                return;
464            } else if (mActivity.mCameraDisabled) {
465                Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
466                return;
467            }
468        } catch (InterruptedException ex) {
469            // ignore
470        }
471
472        showTimeLapseUI(mCaptureTimeLapse);
473        initializeVideoSnapshot();
474        resizeForPreviewAspectRatio();
475
476        initializeVideoControl();
477        mControlEnabled = true;
478        mPendingSwitchCameraId = -1;
479    }
480
481    @Override
482    public void onStop() {}
483
484    private void loadCameraPreferences() {
485        CameraSettings settings = new CameraSettings(mActivity, mParameters,
486                mCameraId, CameraHolder.instance().getCameraInfo());
487        // Remove the video quality preference setting when the quality is given in the intent.
488        mPreferenceGroup = filterPreferenceScreenByIntent(
489                settings.getPreferenceGroup(R.xml.video_preferences));
490    }
491
492    @Override
493    public boolean collapseCameraControls() {
494        if (mPopup != null) {
495            dismissPopup();
496            return true;
497        }
498        return false;
499    }
500
501    private void enableCameraControls(boolean enable) {
502        mControlEnabled = enable;
503    }
504
505    private void initializeVideoControl() {
506        loadCameraPreferences();
507        mVideoControl.initialize(mPreferenceGroup);
508        if (effectsActive()) {
509            mVideoControl.overrideSettings(
510                    CameraSettings.KEY_VIDEO_QUALITY,
511                    Integer.toString(getLowVideoQuality()));
512        }
513    }
514
515    @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
516    private static int getLowVideoQuality() {
517        if (ApiHelper.HAS_FINE_RESOLUTION_QUALITY_LEVELS) {
518            return CamcorderProfile.QUALITY_480P;
519        } else {
520            return CamcorderProfile.QUALITY_LOW;
521        }
522    }
523
524    private class MyOrientationEventListener
525            extends OrientationEventListener {
526        public MyOrientationEventListener(Context context) {
527            super(context);
528        }
529
530        @Override
531        public void onOrientationChanged(int orientation) {
532            // We keep the last known orientation. So if the user first orient
533            // the camera then point the camera to floor or sky, we still have
534            // the correct orientation.
535            if (orientation == ORIENTATION_UNKNOWN) return;
536            int newOrientation = Util.roundOrientation(orientation, mOrientation);
537
538            if (mOrientation != newOrientation) {
539                mOrientation = newOrientation;
540                // The input of effects recorder is affected by
541                // android.hardware.Camera.setDisplayOrientation. Its value only
542                // compensates the camera orientation (no Display.getRotation).
543                // So the orientation hint here should only consider sensor
544                // orientation.
545                if (effectsActive()) {
546                    mEffectsRecorder.setOrientationHint(mOrientation);
547                }
548            }
549
550            // When the screen is unlocked, display rotation may change. Always
551            // calculate the up-to-date orientationCompensation.
552            int orientationCompensation =
553                    (mOrientation + Util.getDisplayRotation(mActivity)) % 360;
554
555            if (mOrientationCompensation != orientationCompensation) {
556                mOrientationCompensation = orientationCompensation;
557                // Do not rotate the icons during recording because the video
558                // orientation is fixed after recording.
559                if (!mMediaRecorderRecording) {
560                    setOrientationIndicator(mOrientationCompensation, true);
561                }
562            }
563
564            // Show the toast after getting the first orientation changed.
565            if (mHandler.hasMessages(SHOW_TAP_TO_SNAPSHOT_TOAST)) {
566                mHandler.removeMessages(SHOW_TAP_TO_SNAPSHOT_TOAST);
567                showTapToSnapshotToast();
568            }
569        }
570    }
571
572    private void setOrientationIndicator(int orientation, boolean animation) {
573        Rotatable[] indicators = {
574                mRenderOverlay,
575                mBgLearningMessageRotater,
576                mReviewDoneButton, mReviewPlayButton, mRotateDialog};
577        for (Rotatable indicator : indicators) {
578            if (indicator != null) indicator.setOrientation(orientation, animation);
579        }
580
581        // We change the orientation of the review cancel button only for tablet
582        // UI because there's a label along with the X icon. For phone UI, we
583        // don't change the orientation because there's only a symmetrical X
584        // icon.
585        if (mReviewCancelButton instanceof RotateLayout) {
586            mReviewCancelButton.setOrientation(orientation, animation);
587        }
588
589        // We change the orientation of the linearlayout only for phone UI because when in portrait
590        // the width is not enough.
591        if (mLabelsLinearLayout != null) {
592            if (((orientation / 90) & 1) == 0) {
593                mLabelsLinearLayout.setOrientation(LinearLayout.VERTICAL);
594            } else {
595                mLabelsLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
596            }
597        }
598        mRecordingTimeRect.setOrientation(mOrientationCompensation, animation);
599    }
600
601    private void startPlayVideoActivity() {
602        Intent intent = new Intent(Intent.ACTION_VIEW);
603        intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat));
604        try {
605            mActivity.startActivity(intent);
606        } catch (ActivityNotFoundException ex) {
607            Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex);
608        }
609    }
610
611    @OnClickAttr
612    public void onThumbnailClicked(View v) {
613        if (!mMediaRecorderRecording && mActivity.mThumbnail != null
614                && !mSwitchingCamera) {
615            mActivity.gotoGallery();
616        }
617    }
618
619    @OnClickAttr
620    public void onReviewRetakeClicked(View v) {
621        deleteCurrentVideo();
622        hideAlert();
623    }
624
625    @OnClickAttr
626    public void onReviewPlayClicked(View v) {
627        startPlayVideoActivity();
628    }
629
630    @OnClickAttr
631    public void onReviewDoneClicked(View v) {
632        doReturnToCaller(true);
633    }
634
635    @OnClickAttr
636    public void onReviewCancelClicked(View v) {
637        stopVideoRecording();
638        doReturnToCaller(false);
639    }
640
641    private void onStopVideoRecording() {
642        mEffectsDisplayResult = true;
643        boolean recordFail = stopVideoRecording();
644        if (mIsVideoCaptureIntent) {
645            if (!effectsActive()) {
646                if (mQuickCapture) {
647                    doReturnToCaller(!recordFail);
648                } else if (!recordFail) {
649                    showAlert();
650                }
651            }
652        } else if (!recordFail){
653            // Start capture animation.
654            if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
655                // The capture animation is disabled on ICS because we use SurfaceView
656                // for preview during recording. When the recording is done, we switch
657                // back to use SurfaceTexture for preview and we need to stop then start
658                // the preview. This will cause the preview flicker since the preview
659                // will not be continuous for a short period of time.
660                ((CameraScreenNail) mActivity.mCameraScreenNail).animateCapture(getCameraRotation());
661            }
662            if (!effectsActive()) getThumbnail();
663        }
664    }
665
666    private int getCameraRotation() {
667        return (mOrientationCompensation - mDisplayRotation + 360) % 360;
668    }
669
670    public void onProtectiveCurtainClick(View v) {
671        // Consume clicks
672    }
673
674    @Override
675    public void onShutterButtonClick() {
676        if (collapseCameraControls() || mSwitchingCamera) return;
677
678        boolean stop = mMediaRecorderRecording;
679
680        if (stop) {
681            onStopVideoRecording();
682        } else {
683            startVideoRecording();
684        }
685        mShutterButton.setEnabled(false);
686
687        // Keep the shutter button disabled when in video capture intent
688        // mode and recording is stopped. It'll be re-enabled when
689        // re-take button is clicked.
690        if (!(mIsVideoCaptureIntent && stop)) {
691            mHandler.sendEmptyMessageDelayed(
692                    ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT);
693        }
694    }
695
696    @Override
697    public void onShutterButtonFocus(boolean pressed) {
698        // Do nothing (everything happens in onShutterButtonClick).
699    }
700
701    private void readVideoPreferences() {
702        // The preference stores values from ListPreference and is thus string type for all values.
703        // We need to convert it to int manually.
704        String defaultQuality = CameraSettings.getDefaultVideoQuality(mCameraId,
705                mActivity.getResources().getString(R.string.pref_video_quality_default));
706        String videoQuality =
707                mPreferences.getString(CameraSettings.KEY_VIDEO_QUALITY,
708                        defaultQuality);
709        int quality = Integer.valueOf(videoQuality);
710
711        // Set video quality.
712        Intent intent = mActivity.getIntent();
713        if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
714            int extraVideoQuality =
715                    intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
716            if (extraVideoQuality > 0) {
717                quality = CamcorderProfile.QUALITY_HIGH;
718            } else {  // 0 is mms.
719                quality = CamcorderProfile.QUALITY_LOW;
720            }
721        }
722
723        // Set video duration limit. The limit is read from the preference,
724        // unless it is specified in the intent.
725        if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
726            int seconds =
727                    intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0);
728            mMaxVideoDurationInMs = 1000 * seconds;
729        } else {
730            mMaxVideoDurationInMs = CameraSettings.DEFAULT_VIDEO_DURATION;
731        }
732
733        // Set effect
734        mEffectType = CameraSettings.readEffectType(mPreferences);
735        if (mEffectType != EffectsRecorder.EFFECT_NONE) {
736            mEffectParameter = CameraSettings.readEffectParameter(mPreferences);
737            // Set quality to be no higher than 480p.
738            CamcorderProfile profile = CamcorderProfile.get(mCameraId, quality);
739            if (profile.videoFrameHeight > 480) {
740                quality = getLowVideoQuality();
741            }
742            // On initial startup, can get here before indicator control is
743            // enabled. In that case, UI quality override handled in
744            // initializeIndicatorControl.
745//            if (mIndicatorControlContainer != null) {
746//                mIndicatorControlContainer.overrideSettings(
747//                        CameraSettings.KEY_VIDEO_QUALITY,
748//                        Integer.toString(getLowVideoQuality()));
749//            }
750        } else {
751            mEffectParameter = null;
752//            if (mIndicatorControlContainer != null) {
753//                mIndicatorControlContainer.overrideSettings(
754//                        CameraSettings.KEY_VIDEO_QUALITY,
755//                        null);
756//            }
757        }
758        // Read time lapse recording interval.
759        if (ApiHelper.HAS_TIME_LAPSE_RECORDING) {
760            String frameIntervalStr = mPreferences.getString(
761                    CameraSettings.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL,
762                    mActivity.getString(R.string.pref_video_time_lapse_frame_interval_default));
763            mTimeBetweenTimeLapseFrameCaptureMs = Integer.parseInt(frameIntervalStr);
764            mCaptureTimeLapse = (mTimeBetweenTimeLapseFrameCaptureMs != 0);
765        }
766        // TODO: This should be checked instead directly +1000.
767        if (mCaptureTimeLapse) quality += 1000;
768        mProfile = CamcorderProfile.get(mCameraId, quality);
769        getDesiredPreviewSize();
770    }
771
772    private void writeDefaultEffectToPrefs()  {
773        ComboPreferences.Editor editor = mPreferences.edit();
774        editor.putString(CameraSettings.KEY_VIDEO_EFFECT,
775                mActivity.getString(R.string.pref_video_effect_default));
776        editor.apply();
777    }
778
779    @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
780    private void getDesiredPreviewSize() {
781        mParameters = mActivity.mCameraDevice.getParameters();
782        if (ApiHelper.HAS_GET_SUPPORTED_VIDEO_SIZE) {
783            if (mParameters.getSupportedVideoSizes() == null || effectsActive()) {
784                mDesiredPreviewWidth = mProfile.videoFrameWidth;
785                mDesiredPreviewHeight = mProfile.videoFrameHeight;
786            } else {  // Driver supports separates outputs for preview and video.
787                List<Size> sizes = mParameters.getSupportedPreviewSizes();
788                Size preferred = mParameters.getPreferredPreviewSizeForVideo();
789                int product = preferred.width * preferred.height;
790                Iterator<Size> it = sizes.iterator();
791                // Remove the preview sizes that are not preferred.
792                while (it.hasNext()) {
793                    Size size = it.next();
794                    if (size.width * size.height > product) {
795                        it.remove();
796                    }
797                }
798                Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes,
799                        (double) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
800                mDesiredPreviewWidth = optimalSize.width;
801                mDesiredPreviewHeight = optimalSize.height;
802            }
803        } else {
804            mDesiredPreviewWidth = mProfile.videoFrameWidth;
805            mDesiredPreviewHeight = mProfile.videoFrameHeight;
806        }
807        Log.v(TAG, "mDesiredPreviewWidth=" + mDesiredPreviewWidth +
808                ". mDesiredPreviewHeight=" + mDesiredPreviewHeight);
809    }
810
811    private void resizeForPreviewAspectRatio() {
812        mPreviewFrameLayout.setAspectRatio(
813                (double) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
814    }
815
816    @Override
817    public void installIntentFilter() {
818        // install an intent filter to receive SD card related events.
819        IntentFilter intentFilter =
820                new IntentFilter(Intent.ACTION_MEDIA_EJECT);
821        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
822        intentFilter.addDataScheme("file");
823        mReceiver = new MyBroadcastReceiver();
824        mActivity.registerReceiver(mReceiver, intentFilter);
825    }
826
827    @Override
828    public void onResumeBeforeSuper() {
829        mPaused = false;
830    }
831
832    @Override
833    public void onResumeAfterSuper() {
834        if (mActivity.mOpenCameraFail || mActivity.mCameraDisabled)
835            return;
836
837        mZoomValue = 0;
838
839        showVideoSnapshotUI(false);
840
841        // Start orientation listener as soon as possible because it takes
842        // some time to get first orientation.
843        mOrientationListener.enable();
844        if (!mPreviewing) {
845            if (resetEffect()) {
846                mBgLearningMessageFrame.setVisibility(View.GONE);
847//                mIndicatorControlContainer.reloadPreferences();
848            }
849            CameraOpenThread cameraOpenThread = new CameraOpenThread();
850            cameraOpenThread.start();
851            try {
852                cameraOpenThread.join();
853                if (mActivity.mOpenCameraFail) {
854                    Util.showErrorAndFinish(mActivity,
855                            R.string.cannot_connect_camera);
856                    return;
857                } else if (mActivity.mCameraDisabled) {
858                    Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
859                    return;
860                }
861            } catch (InterruptedException ex) {
862                // ignore
863            }
864
865            readVideoPreferences();
866            resizeForPreviewAspectRatio();
867            startPreview();
868        }
869
870        // Initializing it here after the preview is started.
871        initializeZoom();
872
873        keepScreenOnAwhile();
874
875        // Initialize location service.
876        boolean recordLocation = RecordLocationPreference.get(mPreferences,
877                mContentResolver);
878        mLocationManager.recordLocation(recordLocation);
879
880        if (!mIsVideoCaptureIntent) {
881            mActivity.getLastThumbnail();
882        }
883
884        if (mPreviewing) {
885            mOnResumeTime = SystemClock.uptimeMillis();
886            mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
887        }
888        // Dismiss open menu if exists.
889        PopupManager.getInstance(mActivity).notifyShowPopup(null);
890
891        mVideoNamer = new VideoNamer();
892    }
893
894    private void setDisplayOrientation() {
895        mDisplayRotation = Util.getDisplayRotation(mActivity);
896        if (ApiHelper.HAS_SURFACE_TEXTURE) {
897            // The display rotation is handled by gallery.
898            mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId);
899        } else {
900            // We need to consider display rotation ourselves.
901            mCameraDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
902        }
903    }
904
905    private void startPreview() {
906        Log.v(TAG, "startPreview");
907
908        mActivity.mCameraDevice.setErrorCallback(mErrorCallback);
909        if (mPreviewing == true) {
910            stopPreview();
911            if (effectsActive() && mEffectsRecorder != null) {
912                mEffectsRecorder.release();
913                mEffectsRecorder = null;
914            }
915        }
916
917        setDisplayOrientation();
918        mActivity.mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
919        setCameraParameters();
920
921        try {
922            if (!effectsActive()) {
923                if (ApiHelper.HAS_SURFACE_TEXTURE) {
924                    mActivity.mCameraDevice.setPreviewTextureAsync(
925                            ((CameraScreenNail) mActivity.mCameraScreenNail).getSurfaceTexture());
926                } else {
927                    mActivity.mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder());
928                }
929                mActivity.mCameraDevice.startPreviewAsync();
930            } else {
931                initializeEffectsPreview();
932                mEffectsRecorder.startPreview();
933            }
934        } catch (Throwable ex) {
935            closeCamera();
936            throw new RuntimeException("startPreview failed", ex);
937        }
938
939        mPreviewing = true;
940    }
941
942    private void stopPreview() {
943        mActivity.mCameraDevice.stopPreview();
944        mPreviewing = false;
945    }
946
947    // Closing the effects out. Will shut down the effects graph.
948    private void closeEffects() {
949        Log.v(TAG, "Closing effects");
950        mEffectType = EffectsRecorder.EFFECT_NONE;
951        if (mEffectsRecorder == null) {
952            Log.d(TAG, "Effects are already closed. Nothing to do");
953            return;
954        }
955        // This call can handle the case where the camera is already released
956        // after the recording has been stopped.
957        mEffectsRecorder.release();
958        mEffectsRecorder = null;
959    }
960
961    // By default, we want to close the effects as well with the camera.
962    private void closeCamera() {
963        closeCamera(true);
964    }
965
966    // In certain cases, when the effects are active, we may want to shutdown
967    // only the camera related parts, and handle closing the effects in the
968    // effectsUpdate callback.
969    // For example, in onPause, we want to make the camera available to
970    // outside world immediately, however, want to wait till the effects
971    // callback to shut down the effects. In such a case, we just disconnect
972    // the effects from the camera by calling disconnectCamera. That way
973    // the effects can handle that when shutting down.
974    //
975    // @param closeEffectsAlso - indicates whether we want to close the
976    // effects also along with the camera.
977    private void closeCamera(boolean closeEffectsAlso) {
978        Log.v(TAG, "closeCamera");
979        if (mActivity.mCameraDevice == null) {
980            Log.d(TAG, "already stopped.");
981            return;
982        }
983
984        if (mEffectsRecorder != null) {
985            // Disconnect the camera from effects so that camera is ready to
986            // be released to the outside world.
987            mEffectsRecorder.disconnectCamera();
988        }
989        if (closeEffectsAlso) closeEffects();
990        mActivity.mCameraDevice.setZoomChangeListener(null);
991        mActivity.mCameraDevice.setErrorCallback(null);
992        CameraHolder.instance().release();
993        mActivity.mCameraDevice = null;
994        mPreviewing = false;
995        mSnapshotInProgress = false;
996    }
997
998    private void releasePreviewResources() {
999        if (ApiHelper.HAS_SURFACE_TEXTURE) {
1000            CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
1001            if (screenNail.getSurfaceTexture() != null) {
1002                screenNail.releaseSurfaceTexture();
1003            }
1004            if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
1005                mHandler.removeMessages(HIDE_SURFACE_VIEW);
1006                mPreviewSurfaceView.setVisibility(View.GONE);
1007            }
1008        }
1009    }
1010
1011    @Override
1012    public void onPauseBeforeSuper() {
1013        mPaused = true;
1014
1015        if (mMediaRecorderRecording) {
1016            // Camera will be released in onStopVideoRecording.
1017            onStopVideoRecording();
1018        } else {
1019            closeCamera();
1020            if (!effectsActive()) releaseMediaRecorder();
1021        }
1022        if (effectsActive()) {
1023            // If the effects are active, make sure we tell the graph that the
1024            // surfacetexture is not valid anymore. Disconnect the graph from
1025            // the display. This should be done before releasing the surface
1026            // texture.
1027            mEffectsRecorder.disconnectDisplay();
1028        } else {
1029            // Close the file descriptor and clear the video namer only if the
1030            // effects are not active. If effects are active, we need to wait
1031            // till we get the callback from the Effects that the graph is done
1032            // recording. That also needs a change in the stopVideoRecording()
1033            // call to not call closeCamera if the effects are active, because
1034            // that will close down the effects are well, thus making this if
1035            // condition invalid.
1036            closeVideoFileDescriptor();
1037            clearVideoNamer();
1038        }
1039
1040        releasePreviewResources();
1041
1042        if (mReceiver != null) {
1043            mActivity.unregisterReceiver(mReceiver);
1044            mReceiver = null;
1045        }
1046        resetScreenOn();
1047
1048        if (mOrientationListener != null) mOrientationListener.disable();
1049        if (mLocationManager != null) mLocationManager.recordLocation(false);
1050
1051        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1052        mHandler.removeMessages(SWITCH_CAMERA);
1053        mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
1054        mPendingSwitchCameraId = -1;
1055        mSwitchingCamera = false;
1056        // Call onPause after stopping video recording. So the camera can be
1057        // released as soon as possible.
1058    }
1059
1060    @Override
1061    public void onPauseAfterSuper() {
1062    }
1063
1064    @Override
1065    public void onUserInteraction() {
1066        if (!mMediaRecorderRecording && !mActivity.isFinishing()) {
1067            keepScreenOnAwhile();
1068        }
1069    }
1070
1071    @Override
1072    public boolean onBackPressed() {
1073        if (mPaused) return true;
1074        if (mMediaRecorderRecording) {
1075            onStopVideoRecording();
1076            return true;
1077        } else {
1078            return collapseCameraControls();
1079        }
1080    }
1081
1082    @Override
1083    public boolean onKeyDown(int keyCode, KeyEvent event) {
1084        // Do not handle any key if the activity is paused.
1085        if (mPaused) {
1086            return true;
1087        }
1088
1089        switch (keyCode) {
1090            case KeyEvent.KEYCODE_CAMERA:
1091                if (event.getRepeatCount() == 0) {
1092                    mShutterButton.performClick();
1093                    return true;
1094                }
1095                break;
1096            case KeyEvent.KEYCODE_DPAD_CENTER:
1097                if (event.getRepeatCount() == 0) {
1098                    mShutterButton.performClick();
1099                    return true;
1100                }
1101                break;
1102            case KeyEvent.KEYCODE_MENU:
1103                if (mMediaRecorderRecording) return true;
1104                break;
1105        }
1106        return false;
1107    }
1108
1109    @Override
1110    public boolean onKeyUp(int keyCode, KeyEvent event) {
1111        switch (keyCode) {
1112            case KeyEvent.KEYCODE_CAMERA:
1113                mShutterButton.setPressed(false);
1114                return true;
1115        }
1116        return false;
1117    }
1118
1119    private boolean isVideoCaptureIntent() {
1120        String action = mActivity.getIntent().getAction();
1121        return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action));
1122    }
1123
1124    private void doReturnToCaller(boolean valid) {
1125        Intent resultIntent = new Intent();
1126        int resultCode;
1127        if (valid) {
1128            resultCode = Activity.RESULT_OK;
1129            resultIntent.setData(mCurrentVideoUri);
1130        } else {
1131            resultCode = Activity.RESULT_CANCELED;
1132        }
1133        mActivity.setResultEx(resultCode, resultIntent);
1134        mActivity.finish();
1135    }
1136
1137    private void cleanupEmptyFile() {
1138        if (mVideoFilename != null) {
1139            File f = new File(mVideoFilename);
1140            if (f.length() == 0 && f.delete()) {
1141                Log.v(TAG, "Empty video file deleted: " + mVideoFilename);
1142                mVideoFilename = null;
1143            }
1144        }
1145    }
1146
1147    private void setupMediaRecorderPreviewDisplay() {
1148        // Nothing to do here if using SurfaceTexture.
1149        if (!ApiHelper.HAS_SURFACE_TEXTURE) {
1150            mMediaRecorder.setPreviewDisplay(mPreviewSurfaceView.getHolder().getSurface());
1151        } else if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
1152            // We stop the preview here before unlocking the device because we
1153            // need to change the SurfaceTexture to SurfaceView for preview.
1154            stopPreview();
1155            mActivity.mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder());
1156            // The orientation for SurfaceTexture is different from that for
1157            // SurfaceView. For SurfaceTexture we don't need to consider the
1158            // display rotation. Just consider the sensor's orientation and we
1159            // will set the orientation correctly when showing the texture.
1160            // Gallery will handle the orientation for the preview. For
1161            // SurfaceView we will have to take everything into account so the
1162            // display rotation is considered.
1163            mActivity.mCameraDevice.setDisplayOrientation(
1164                    Util.getDisplayOrientation(mDisplayRotation, mCameraId));
1165            mActivity.mCameraDevice.startPreviewAsync();
1166            mPreviewing = true;
1167            mMediaRecorder.setPreviewDisplay(mPreviewSurfaceView.getHolder().getSurface());
1168        }
1169    }
1170
1171    // Prepares media recorder.
1172    private void initializeRecorder() {
1173        Log.v(TAG, "initializeRecorder");
1174        // If the mCameraDevice is null, then this activity is going to finish
1175        if (mActivity.mCameraDevice == null) return;
1176
1177        if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING && ApiHelper.HAS_SURFACE_TEXTURE) {
1178            // Set the SurfaceView to visible so the surface gets created.
1179            // surfaceCreated() is called immediately when the visibility is
1180            // changed to visible. Thus, mSurfaceViewReady should become true
1181            // right after calling setVisibility().
1182            mPreviewSurfaceView.setVisibility(View.VISIBLE);
1183            if (!mSurfaceViewReady) return;
1184        }
1185
1186        Intent intent = mActivity.getIntent();
1187        Bundle myExtras = intent.getExtras();
1188
1189        long requestedSizeLimit = 0;
1190        closeVideoFileDescriptor();
1191        if (mIsVideoCaptureIntent && myExtras != null) {
1192            Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1193            if (saveUri != null) {
1194                try {
1195                    mVideoFileDescriptor =
1196                            mContentResolver.openFileDescriptor(saveUri, "rw");
1197                    mCurrentVideoUri = saveUri;
1198                } catch (java.io.FileNotFoundException ex) {
1199                    // invalid uri
1200                    Log.e(TAG, ex.toString());
1201                }
1202            }
1203            requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
1204        }
1205        mMediaRecorder = new MediaRecorder();
1206
1207        setupMediaRecorderPreviewDisplay();
1208        // Unlock the camera object before passing it to media recorder.
1209        mActivity.mCameraDevice.unlock();
1210        mMediaRecorder.setCamera(mActivity.mCameraDevice.getCamera());
1211        if (!mCaptureTimeLapse) {
1212            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
1213        }
1214        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
1215        mMediaRecorder.setProfile(mProfile);
1216        mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs);
1217        if (mCaptureTimeLapse) {
1218            double fps = 1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs;
1219            setCaptureRate(mMediaRecorder, fps);
1220        }
1221
1222        setRecordLocation();
1223
1224        // Set output file.
1225        // Try Uri in the intent first. If it doesn't exist, use our own
1226        // instead.
1227        if (mVideoFileDescriptor != null) {
1228            mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
1229        } else {
1230            generateVideoFilename(mProfile.fileFormat);
1231            mMediaRecorder.setOutputFile(mVideoFilename);
1232        }
1233
1234        // Set maximum file size.
1235        long maxFileSize = mActivity.getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD;
1236        if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
1237            maxFileSize = requestedSizeLimit;
1238        }
1239
1240        try {
1241            mMediaRecorder.setMaxFileSize(maxFileSize);
1242        } catch (RuntimeException exception) {
1243            // We are going to ignore failure of setMaxFileSize here, as
1244            // a) The composer selected may simply not support it, or
1245            // b) The underlying media framework may not handle 64-bit range
1246            // on the size restriction.
1247        }
1248
1249        // See android.hardware.Camera.Parameters.setRotation for
1250        // documentation.
1251        // Note that mOrientation here is the device orientation, which is the opposite of
1252        // what activity.getWindowManager().getDefaultDisplay().getRotation() would return,
1253        // which is the orientation the graphics need to rotate in order to render correctly.
1254        int rotation = 0;
1255        if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
1256            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
1257            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
1258                rotation = (info.orientation - mOrientation + 360) % 360;
1259            } else {  // back-facing camera
1260                rotation = (info.orientation + mOrientation) % 360;
1261            }
1262        }
1263        mMediaRecorder.setOrientationHint(rotation);
1264        mOrientationCompensationAtRecordStart = mOrientationCompensation;
1265
1266        try {
1267            mMediaRecorder.prepare();
1268        } catch (IOException e) {
1269            Log.e(TAG, "prepare failed for " + mVideoFilename, e);
1270            releaseMediaRecorder();
1271            throw new RuntimeException(e);
1272        }
1273
1274        mMediaRecorder.setOnErrorListener(this);
1275        mMediaRecorder.setOnInfoListener(this);
1276    }
1277
1278    @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
1279    private static void setCaptureRate(MediaRecorder recorder, double fps) {
1280        recorder.setCaptureRate(fps);
1281    }
1282
1283    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
1284    private void setRecordLocation() {
1285        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1286            Location loc = mLocationManager.getCurrentLocation();
1287            if (loc != null) {
1288                mMediaRecorder.setLocation((float) loc.getLatitude(),
1289                        (float) loc.getLongitude());
1290            }
1291        }
1292    }
1293
1294    private void initializeEffectsPreview() {
1295        Log.v(TAG, "initializeEffectsPreview");
1296        // If the mCameraDevice is null, then this activity is going to finish
1297        if (mActivity.mCameraDevice == null) return;
1298
1299        boolean inLandscape = (mActivity.getResources().getConfiguration().orientation
1300                == Configuration.ORIENTATION_LANDSCAPE);
1301
1302        CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
1303
1304        mEffectsDisplayResult = false;
1305        mEffectsRecorder = new EffectsRecorder(mActivity);
1306
1307        // TODO: Confirm none of the following need to go to initializeEffectsRecording()
1308        // and none of these change even when the preview is not refreshed.
1309        mEffectsRecorder.setCameraDisplayOrientation(mCameraDisplayOrientation);
1310        mEffectsRecorder.setCamera(mActivity.mCameraDevice);
1311        mEffectsRecorder.setCameraFacing(info.facing);
1312        mEffectsRecorder.setProfile(mProfile);
1313        mEffectsRecorder.setEffectsListener(this);
1314        mEffectsRecorder.setOnInfoListener(this);
1315        mEffectsRecorder.setOnErrorListener(this);
1316
1317        // The input of effects recorder is affected by
1318        // android.hardware.Camera.setDisplayOrientation. Its value only
1319        // compensates the camera orientation (no Display.getRotation). So the
1320        // orientation hint here should only consider sensor orientation.
1321        int orientation = 0;
1322        if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
1323            orientation = mOrientation;
1324        }
1325        mEffectsRecorder.setOrientationHint(orientation);
1326
1327        mOrientationCompensationAtRecordStart = mOrientationCompensation;
1328
1329        CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
1330        mEffectsRecorder.setPreviewSurfaceTexture(screenNail.getSurfaceTexture(),
1331                screenNail.getWidth(), screenNail.getHeight());
1332
1333        if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER &&
1334                ((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) {
1335            mEffectsRecorder.setEffect(mEffectType, mEffectUriFromGallery);
1336        } else {
1337            mEffectsRecorder.setEffect(mEffectType, mEffectParameter);
1338        }
1339    }
1340
1341    private void initializeEffectsRecording() {
1342        Log.v(TAG, "initializeEffectsRecording");
1343
1344        Intent intent = mActivity.getIntent();
1345        Bundle myExtras = intent.getExtras();
1346
1347        long requestedSizeLimit = 0;
1348        closeVideoFileDescriptor();
1349        if (mIsVideoCaptureIntent && myExtras != null) {
1350            Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1351            if (saveUri != null) {
1352                try {
1353                    mVideoFileDescriptor =
1354                            mContentResolver.openFileDescriptor(saveUri, "rw");
1355                    mCurrentVideoUri = saveUri;
1356                } catch (java.io.FileNotFoundException ex) {
1357                    // invalid uri
1358                    Log.e(TAG, ex.toString());
1359                }
1360            }
1361            requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
1362        }
1363
1364        mEffectsRecorder.setProfile(mProfile);
1365        // important to set the capture rate to zero if not timelapsed, since the
1366        // effectsrecorder object does not get created again for each recording
1367        // session
1368        if (mCaptureTimeLapse) {
1369            mEffectsRecorder.setCaptureRate((1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs));
1370        } else {
1371            mEffectsRecorder.setCaptureRate(0);
1372        }
1373
1374        // Set output file
1375        if (mVideoFileDescriptor != null) {
1376            mEffectsRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
1377        } else {
1378            generateVideoFilename(mProfile.fileFormat);
1379            mEffectsRecorder.setOutputFile(mVideoFilename);
1380        }
1381
1382        // Set maximum file size.
1383        long maxFileSize = mActivity.getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD;
1384        if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
1385            maxFileSize = requestedSizeLimit;
1386        }
1387        mEffectsRecorder.setMaxFileSize(maxFileSize);
1388        mEffectsRecorder.setMaxDuration(mMaxVideoDurationInMs);
1389    }
1390
1391
1392    private void releaseMediaRecorder() {
1393        Log.v(TAG, "Releasing media recorder.");
1394        if (mMediaRecorder != null) {
1395            cleanupEmptyFile();
1396            mMediaRecorder.reset();
1397            mMediaRecorder.release();
1398            mMediaRecorder = null;
1399        }
1400        mVideoFilename = null;
1401    }
1402
1403    private void releaseEffectsRecorder() {
1404        Log.v(TAG, "Releasing effects recorder.");
1405        if (mEffectsRecorder != null) {
1406            cleanupEmptyFile();
1407            mEffectsRecorder.release();
1408            mEffectsRecorder = null;
1409        }
1410        mEffectType = EffectsRecorder.EFFECT_NONE;
1411        mVideoFilename = null;
1412    }
1413
1414    private void generateVideoFilename(int outputFileFormat) {
1415        long dateTaken = System.currentTimeMillis();
1416        String title = createName(dateTaken);
1417        // Used when emailing.
1418        String filename = title + convertOutputFormatToFileExt(outputFileFormat);
1419        String mime = convertOutputFormatToMimeType(outputFileFormat);
1420        String path = Storage.DIRECTORY + '/' + filename;
1421        String tmpPath = path + ".tmp";
1422        mCurrentVideoValues = new ContentValues(7);
1423        mCurrentVideoValues.put(Video.Media.TITLE, title);
1424        mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename);
1425        mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken);
1426        mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime);
1427        mCurrentVideoValues.put(Video.Media.DATA, path);
1428        mCurrentVideoValues.put(Video.Media.RESOLUTION,
1429                Integer.toString(mProfile.videoFrameWidth) + "x" +
1430                Integer.toString(mProfile.videoFrameHeight));
1431        Location loc = mLocationManager.getCurrentLocation();
1432        if (loc != null) {
1433            mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude());
1434            mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude());
1435        }
1436        mVideoNamer.prepareUri(mContentResolver, mCurrentVideoValues);
1437        mVideoFilename = tmpPath;
1438        Log.v(TAG, "New video filename: " + mVideoFilename);
1439    }
1440
1441    private boolean addVideoToMediaStore() {
1442        boolean fail = false;
1443        if (mVideoFileDescriptor == null) {
1444            mCurrentVideoValues.put(Video.Media.SIZE,
1445                    new File(mCurrentVideoFilename).length());
1446            long duration = SystemClock.uptimeMillis() - mRecordingStartTime;
1447            if (duration > 0) {
1448                if (mCaptureTimeLapse) {
1449                    duration = getTimeLapseVideoLength(duration);
1450                }
1451                mCurrentVideoValues.put(Video.Media.DURATION, duration);
1452            } else {
1453                Log.w(TAG, "Video duration <= 0 : " + duration);
1454            }
1455            try {
1456                mCurrentVideoUri = mVideoNamer.getUri();
1457                mActivity.addSecureAlbumItemIfNeeded(true, mCurrentVideoUri);
1458
1459                // Rename the video file to the final name. This avoids other
1460                // apps reading incomplete data.  We need to do it after the
1461                // above mVideoNamer.getUri() call, so we are certain that the
1462                // previous insert to MediaProvider is completed.
1463                String finalName = mCurrentVideoValues.getAsString(
1464                        Video.Media.DATA);
1465                if (new File(mCurrentVideoFilename).renameTo(new File(finalName))) {
1466                    mCurrentVideoFilename = finalName;
1467                }
1468
1469                mContentResolver.update(mCurrentVideoUri, mCurrentVideoValues
1470                        , null, null);
1471                mActivity.sendBroadcast(new Intent(Util.ACTION_NEW_VIDEO,
1472                        mCurrentVideoUri));
1473            } catch (Exception e) {
1474                // We failed to insert into the database. This can happen if
1475                // the SD card is unmounted.
1476                Log.e(TAG, "failed to add video to media store", e);
1477                mCurrentVideoUri = null;
1478                mCurrentVideoFilename = null;
1479                fail = true;
1480            } finally {
1481                Log.v(TAG, "Current video URI: " + mCurrentVideoUri);
1482            }
1483        }
1484        mCurrentVideoValues = null;
1485        return fail;
1486    }
1487
1488    private void deleteCurrentVideo() {
1489        // Remove the video and the uri if the uri is not passed in by intent.
1490        if (mCurrentVideoFilename != null) {
1491            deleteVideoFile(mCurrentVideoFilename);
1492            mCurrentVideoFilename = null;
1493            if (mCurrentVideoUri != null) {
1494                mContentResolver.delete(mCurrentVideoUri, null, null);
1495                mCurrentVideoUri = null;
1496            }
1497        }
1498        mActivity.updateStorageSpaceAndHint();
1499    }
1500
1501    private void deleteVideoFile(String fileName) {
1502        Log.v(TAG, "Deleting video " + fileName);
1503        File f = new File(fileName);
1504        if (!f.delete()) {
1505            Log.v(TAG, "Could not delete " + fileName);
1506        }
1507    }
1508
1509    private PreferenceGroup filterPreferenceScreenByIntent(
1510            PreferenceGroup screen) {
1511        Intent intent = mActivity.getIntent();
1512        if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
1513            CameraSettings.removePreferenceFromScreen(screen,
1514                    CameraSettings.KEY_VIDEO_QUALITY);
1515        }
1516
1517        if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
1518            CameraSettings.removePreferenceFromScreen(screen,
1519                    CameraSettings.KEY_VIDEO_QUALITY);
1520        }
1521        return screen;
1522    }
1523
1524    // from MediaRecorder.OnErrorListener
1525    @Override
1526    public void onError(MediaRecorder mr, int what, int extra) {
1527        Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra);
1528        if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
1529            // We may have run out of space on the sdcard.
1530            stopVideoRecording();
1531            mActivity.updateStorageSpaceAndHint();
1532        }
1533    }
1534
1535    // from MediaRecorder.OnInfoListener
1536    @Override
1537    public void onInfo(MediaRecorder mr, int what, int extra) {
1538        if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
1539            if (mMediaRecorderRecording) onStopVideoRecording();
1540        } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
1541            if (mMediaRecorderRecording) onStopVideoRecording();
1542
1543            // Show the toast.
1544            Toast.makeText(mActivity, R.string.video_reach_size_limit,
1545                    Toast.LENGTH_LONG).show();
1546        }
1547    }
1548
1549    /*
1550     * Make sure we're not recording music playing in the background, ask the
1551     * MediaPlaybackService to pause playback.
1552     */
1553    private void pauseAudioPlayback() {
1554        // Shamelessly copied from MediaPlaybackService.java, which
1555        // should be public, but isn't.
1556        Intent i = new Intent("com.android.music.musicservicecommand");
1557        i.putExtra("command", "pause");
1558
1559        mActivity.sendBroadcast(i);
1560    }
1561
1562    // For testing.
1563    public boolean isRecording() {
1564        return mMediaRecorderRecording;
1565    }
1566
1567    private void startVideoRecording() {
1568        Log.v(TAG, "startVideoRecording");
1569        mActivity.setSwipingEnabled(false);
1570        mActivity.hideSwitcher(R.drawable.ic_switch_video_active);
1571
1572        mActivity.updateStorageSpaceAndHint();
1573        if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
1574            Log.v(TAG, "Storage issue, ignore the start request");
1575            return;
1576        }
1577
1578        mCurrentVideoUri = null;
1579        if (effectsActive()) {
1580            initializeEffectsRecording();
1581            if (mEffectsRecorder == null) {
1582                Log.e(TAG, "Fail to initialize effect recorder");
1583                return;
1584            }
1585        } else {
1586            initializeRecorder();
1587            if (mMediaRecorder == null) {
1588                Log.e(TAG, "Fail to initialize media recorder");
1589                return;
1590            }
1591        }
1592
1593        pauseAudioPlayback();
1594
1595        if (effectsActive()) {
1596            try {
1597                mEffectsRecorder.startRecording();
1598            } catch (RuntimeException e) {
1599                Log.e(TAG, "Could not start effects recorder. ", e);
1600                releaseEffectsRecorder();
1601                return;
1602            }
1603        } else {
1604            try {
1605                mMediaRecorder.start(); // Recording is now started
1606            } catch (RuntimeException e) {
1607                Log.e(TAG, "Could not start media recorder. ", e);
1608                releaseMediaRecorder();
1609                // If start fails, frameworks will not lock the camera for us.
1610                mActivity.mCameraDevice.lock();
1611                return;
1612            }
1613        }
1614
1615        // The parameters may have been changed by MediaRecorder upon starting
1616        // recording. We need to alter the parameters if we support camcorder
1617        // zoom. To reduce latency when setting the parameters during zoom, we
1618        // update mParameters here once.
1619        if (ApiHelper.HAS_ZOOM_WHEN_RECORDING) {
1620            mParameters = mActivity.mCameraDevice.getParameters();
1621        }
1622
1623        enableCameraControls(false);
1624
1625        mMediaRecorderRecording = true;
1626        mRecordingStartTime = SystemClock.uptimeMillis();
1627        showRecordingUI(true);
1628
1629        updateRecordingTime();
1630        keepScreenOn();
1631    }
1632
1633    private void showRecordingUI(boolean recording) {
1634        if (recording) {
1635            if (mActivity.mThumbnailView != null) mActivity.mThumbnailView.setEnabled(false);
1636//            mShutterButton.setImageResource(R.drawable.btn_shutter_video_recording);
1637            mRecordingTimeView.setText("");
1638            mRecordingTimeView.setVisibility(View.VISIBLE);
1639            if (mReviewControl != null) mReviewControl.setVisibility(View.GONE);
1640            if (mCaptureTimeLapse) {
1641//                mIndicatorControlContainer.startTimeLapseAnimation(
1642//                        mTimeBetweenTimeLapseFrameCaptureMs,
1643//                        mRecordingStartTime);
1644            }
1645            // The camera is not allowed to be accessed in older api levels during
1646            // recording. It is therefore necessary to hide the zoom UI on older
1647            // platforms.
1648            // See the documentation of android.media.MediaRecorder.start() for
1649            // further explanation.
1650            if (!ApiHelper.HAS_ZOOM_WHEN_RECORDING
1651                    && mParameters.isZoomSupported()) {
1652//                mZoomControl.setVisibility(View.GONE);
1653            }
1654        } else {
1655            if (mActivity.mThumbnailView != null) mActivity.mThumbnailView.setEnabled(true);
1656//            mShutterButton.setImageResource(R.drawable.btn_shutter_video);
1657            mRecordingTimeView.setVisibility(View.GONE);
1658            if (mReviewControl != null) mReviewControl.setVisibility(View.VISIBLE);
1659            if (mCaptureTimeLapse) {
1660//                mIndicatorControlContainer.stopTimeLapseAnimation();
1661            }
1662            if (!ApiHelper.HAS_ZOOM_WHEN_RECORDING
1663                    && mParameters.isZoomSupported()) {
1664//                mZoomControl.setVisibility(View.VISIBLE);
1665            }
1666        }
1667    }
1668
1669    private void getThumbnail() {
1670        if (mCurrentVideoUri != null) {
1671            Bitmap videoFrame = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename,
1672                    Math.max(mActivity.mThumbnailViewWidth, MIN_THUMB_SIZE));
1673            if (videoFrame != null) {
1674                mActivity.mThumbnail = Thumbnail.createThumbnail(mCurrentVideoUri, videoFrame, 0);
1675                if (mActivity.mThumbnailView != null) {
1676                    mActivity.mThumbnailView.setBitmap(mActivity.mThumbnail.getBitmap());
1677                }
1678            }
1679        }
1680    }
1681
1682    private void showAlert() {
1683        Bitmap bitmap = null;
1684        if (mVideoFileDescriptor != null) {
1685            bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
1686                    mPreviewFrameLayout.getWidth());
1687        } else if (mCurrentVideoFilename != null) {
1688            bitmap = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename,
1689                    mPreviewFrameLayout.getWidth());
1690        }
1691        if (bitmap != null) {
1692            // MetadataRetriever already rotates the thumbnail. We should rotate
1693            // it to match the UI orientation (and mirror if it is front-facing camera).
1694            CameraInfo[] info = CameraHolder.instance().getCameraInfo();
1695            boolean mirror = (info[mCameraId].facing == CameraInfo.CAMERA_FACING_FRONT);
1696            bitmap = Util.rotateAndMirror(bitmap, -mOrientationCompensationAtRecordStart,
1697                    mirror);
1698            mReviewImage.setImageBitmap(bitmap);
1699            mReviewImage.setVisibility(View.VISIBLE);
1700        }
1701
1702        Util.fadeOut(mShutterButton);
1703
1704        Util.fadeIn((View) mReviewDoneButton);
1705        Util.fadeIn(mReviewPlayButton);
1706
1707        showTimeLapseUI(false);
1708    }
1709
1710    private void hideAlert() {
1711        mReviewImage.setVisibility(View.GONE);
1712        mShutterButton.setEnabled(true);
1713        enableCameraControls(true);
1714
1715        Util.fadeOut((View) mReviewDoneButton);
1716        Util.fadeOut(mReviewPlayButton);
1717
1718        Util.fadeIn(mShutterButton);
1719
1720        if (mCaptureTimeLapse) {
1721            showTimeLapseUI(true);
1722        }
1723    }
1724
1725    private boolean stopVideoRecording() {
1726        Log.v(TAG, "stopVideoRecording");
1727        mActivity.setSwipingEnabled(true);
1728        mActivity.showSwitcher();
1729
1730        boolean fail = false;
1731        if (mMediaRecorderRecording) {
1732            boolean shouldAddToMediaStoreNow = false;
1733
1734            try {
1735                if (effectsActive()) {
1736                    // This is asynchronous, so we can't add to media store now because thumbnail
1737                    // may not be ready. In such case addVideoToMediaStore is called later
1738                    // through a callback from the MediaEncoderFilter to EffectsRecorder,
1739                    // and then to the VideoCamera.
1740                    mEffectsRecorder.stopRecording();
1741                } else {
1742                    mMediaRecorder.setOnErrorListener(null);
1743                    mMediaRecorder.setOnInfoListener(null);
1744                    mMediaRecorder.stop();
1745                    shouldAddToMediaStoreNow = true;
1746                }
1747                mCurrentVideoFilename = mVideoFilename;
1748                Log.v(TAG, "stopVideoRecording: Setting current video filename: "
1749                        + mCurrentVideoFilename);
1750            } catch (RuntimeException e) {
1751                Log.e(TAG, "stop fail",  e);
1752                if (mVideoFilename != null) deleteVideoFile(mVideoFilename);
1753                fail = true;
1754            }
1755            mMediaRecorderRecording = false;
1756
1757            // If the activity is paused, this means activity is interrupted
1758            // during recording. Release the camera as soon as possible because
1759            // face unlock or other applications may need to use the camera.
1760            // However, if the effects are active, then we can only release the
1761            // camera and cannot release the effects recorder since that will
1762            // stop the graph. It is possible to separate out the Camera release
1763            // part and the effects release part. However, the effects recorder
1764            // does hold on to the camera, hence, it needs to be "disconnected"
1765            // from the camera in the closeCamera call.
1766            if (mPaused) {
1767                // Closing only the camera part if effects active. Effects will
1768                // be closed in the callback from effects.
1769                boolean closeEffects = !effectsActive();
1770                closeCamera(closeEffects);
1771            }
1772
1773            showRecordingUI(false);
1774            if (!mIsVideoCaptureIntent) {
1775                enableCameraControls(true);
1776            }
1777            // The orientation was fixed during video recording. Now make it
1778            // reflect the device orientation as video recording is stopped.
1779            setOrientationIndicator(mOrientationCompensation, true);
1780            keepScreenOnAwhile();
1781            if (shouldAddToMediaStoreNow) {
1782                if (addVideoToMediaStore()) fail = true;
1783            }
1784        }
1785        // always release media recorder if no effects running
1786        if (!effectsActive()) {
1787            releaseMediaRecorder();
1788            if (!mPaused) {
1789                mActivity.mCameraDevice.lock();
1790                if (ApiHelper.HAS_SURFACE_TEXTURE &&
1791                    !ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
1792                    stopPreview();
1793                    // Switch back to use SurfaceTexture for preview.
1794                    ((CameraScreenNail) mActivity.mCameraScreenNail).setOneTimeOnFrameDrawnListener(
1795                            mFrameDrawnListener);
1796                    startPreview();
1797                }
1798            }
1799        }
1800        // Update the parameters here because the parameters might have been altered
1801        // by MediaRecorder.
1802        if (!mPaused) mParameters = mActivity.mCameraDevice.getParameters();
1803        return fail;
1804    }
1805
1806    private void resetScreenOn() {
1807        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1808        mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1809    }
1810
1811    private void keepScreenOnAwhile() {
1812        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1813        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1814        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1815    }
1816
1817    private void keepScreenOn() {
1818        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1819        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1820    }
1821
1822    private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
1823        long seconds = milliSeconds / 1000; // round down to compute seconds
1824        long minutes = seconds / 60;
1825        long hours = minutes / 60;
1826        long remainderMinutes = minutes - (hours * 60);
1827        long remainderSeconds = seconds - (minutes * 60);
1828
1829        StringBuilder timeStringBuilder = new StringBuilder();
1830
1831        // Hours
1832        if (hours > 0) {
1833            if (hours < 10) {
1834                timeStringBuilder.append('0');
1835            }
1836            timeStringBuilder.append(hours);
1837
1838            timeStringBuilder.append(':');
1839        }
1840
1841        // Minutes
1842        if (remainderMinutes < 10) {
1843            timeStringBuilder.append('0');
1844        }
1845        timeStringBuilder.append(remainderMinutes);
1846        timeStringBuilder.append(':');
1847
1848        // Seconds
1849        if (remainderSeconds < 10) {
1850            timeStringBuilder.append('0');
1851        }
1852        timeStringBuilder.append(remainderSeconds);
1853
1854        // Centi seconds
1855        if (displayCentiSeconds) {
1856            timeStringBuilder.append('.');
1857            long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
1858            if (remainderCentiSeconds < 10) {
1859                timeStringBuilder.append('0');
1860            }
1861            timeStringBuilder.append(remainderCentiSeconds);
1862        }
1863
1864        return timeStringBuilder.toString();
1865    }
1866
1867    private long getTimeLapseVideoLength(long deltaMs) {
1868        // For better approximation calculate fractional number of frames captured.
1869        // This will update the video time at a higher resolution.
1870        double numberOfFrames = (double) deltaMs / mTimeBetweenTimeLapseFrameCaptureMs;
1871        return (long) (numberOfFrames / mProfile.videoFrameRate * 1000);
1872    }
1873
1874    private void updateRecordingTime() {
1875        if (!mMediaRecorderRecording) {
1876            return;
1877        }
1878        long now = SystemClock.uptimeMillis();
1879        long delta = now - mRecordingStartTime;
1880
1881        // Starting a minute before reaching the max duration
1882        // limit, we'll countdown the remaining time instead.
1883        boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
1884                && delta >= mMaxVideoDurationInMs - 60000);
1885
1886        long deltaAdjusted = delta;
1887        if (countdownRemainingTime) {
1888            deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
1889        }
1890        String text;
1891
1892        long targetNextUpdateDelay;
1893        if (!mCaptureTimeLapse) {
1894            text = millisecondToTimeString(deltaAdjusted, false);
1895            targetNextUpdateDelay = 1000;
1896        } else {
1897            // The length of time lapse video is different from the length
1898            // of the actual wall clock time elapsed. Display the video length
1899            // only in format hh:mm:ss.dd, where dd are the centi seconds.
1900            text = millisecondToTimeString(getTimeLapseVideoLength(delta), true);
1901            targetNextUpdateDelay = mTimeBetweenTimeLapseFrameCaptureMs;
1902        }
1903
1904        mRecordingTimeView.setText(text);
1905
1906        if (mRecordingTimeCountsDown != countdownRemainingTime) {
1907            // Avoid setting the color on every update, do it only
1908            // when it needs changing.
1909            mRecordingTimeCountsDown = countdownRemainingTime;
1910
1911            int color = mActivity.getResources().getColor(countdownRemainingTime
1912                    ? R.color.recording_time_remaining_text
1913                    : R.color.recording_time_elapsed_text);
1914
1915            mRecordingTimeView.setTextColor(color);
1916        }
1917
1918        long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
1919        mHandler.sendEmptyMessageDelayed(
1920                UPDATE_RECORD_TIME, actualNextUpdateDelay);
1921    }
1922
1923    private static boolean isSupported(String value, List<String> supported) {
1924        return supported == null ? false : supported.indexOf(value) >= 0;
1925    }
1926
1927    @SuppressWarnings("deprecation")
1928    private void setCameraParameters() {
1929        mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
1930        mParameters.setPreviewFrameRate(mProfile.videoFrameRate);
1931
1932        // Set flash mode.
1933        String flashMode;
1934        if (mActivity.mShowCameraAppView) {
1935            flashMode = mPreferences.getString(
1936                    CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE,
1937                    mActivity.getString(R.string.pref_camera_video_flashmode_default));
1938        } else {
1939            flashMode = Parameters.FLASH_MODE_OFF;
1940        }
1941        List<String> supportedFlash = mParameters.getSupportedFlashModes();
1942        if (isSupported(flashMode, supportedFlash)) {
1943            mParameters.setFlashMode(flashMode);
1944        } else {
1945            flashMode = mParameters.getFlashMode();
1946            if (flashMode == null) {
1947                flashMode = mActivity.getString(
1948                        R.string.pref_camera_flashmode_no_flash);
1949            }
1950        }
1951
1952        // Set white balance parameter.
1953        String whiteBalance = mPreferences.getString(
1954                CameraSettings.KEY_WHITE_BALANCE,
1955                mActivity.getString(R.string.pref_camera_whitebalance_default));
1956        if (isSupported(whiteBalance,
1957                mParameters.getSupportedWhiteBalance())) {
1958            mParameters.setWhiteBalance(whiteBalance);
1959        } else {
1960            whiteBalance = mParameters.getWhiteBalance();
1961            if (whiteBalance == null) {
1962                whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1963            }
1964        }
1965
1966        // Set zoom.
1967        if (mParameters.isZoomSupported()) {
1968            mParameters.setZoom(mZoomValue);
1969        }
1970
1971        // Set continuous autofocus.
1972        List<String> supportedFocus = mParameters.getSupportedFocusModes();
1973        if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) {
1974            mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
1975        }
1976
1977        mParameters.set(Util.RECORDING_HINT, Util.TRUE);
1978
1979        // Enable video stabilization. Convenience methods not available in API
1980        // level <= 14
1981        String vstabSupported = mParameters.get("video-stabilization-supported");
1982        if ("true".equals(vstabSupported)) {
1983            mParameters.set("video-stabilization", "true");
1984        }
1985
1986        // Set picture size.
1987        // The logic here is different from the logic in still-mode camera.
1988        // There we determine the preview size based on the picture size, but
1989        // here we determine the picture size based on the preview size.
1990        List<Size> supported = mParameters.getSupportedPictureSizes();
1991        Size optimalSize = Util.getOptimalVideoSnapshotPictureSize(supported,
1992                (double) mDesiredPreviewWidth / mDesiredPreviewHeight);
1993        Size original = mParameters.getPictureSize();
1994        if (!original.equals(optimalSize)) {
1995            mParameters.setPictureSize(optimalSize.width, optimalSize.height);
1996        }
1997        Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" +
1998                optimalSize.height);
1999
2000        // Set JPEG quality.
2001        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
2002                CameraProfile.QUALITY_HIGH);
2003        mParameters.setJpegQuality(jpegQuality);
2004
2005        mActivity.mCameraDevice.setParameters(mParameters);
2006        // Keep preview size up to date.
2007        mParameters = mActivity.mCameraDevice.getParameters();
2008
2009        updateCameraScreenNailSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
2010    }
2011
2012    private void updateCameraScreenNailSize(int width, int height) {
2013        if (!ApiHelper.HAS_SURFACE_TEXTURE) return;
2014
2015        if (mCameraDisplayOrientation % 180 != 0) {
2016            int tmp = width;
2017            width = height;
2018            height = tmp;
2019        }
2020
2021        CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
2022        int oldWidth = screenNail.getWidth();
2023        int oldHeight = screenNail.getHeight();
2024
2025        if (oldWidth != width || oldHeight != height) {
2026            screenNail.setSize(width, height);
2027            mActivity.notifyScreenNailChanged();
2028        }
2029
2030        if (screenNail.getSurfaceTexture() == null) {
2031            screenNail.acquireSurfaceTexture();
2032        }
2033    }
2034
2035    @Override
2036    public void onActivityResult(int requestCode, int resultCode, Intent data) {
2037        switch (requestCode) {
2038            case REQUEST_EFFECT_BACKDROPPER:
2039                if (resultCode == Activity.RESULT_OK) {
2040                    // onActivityResult() runs before onResume(), so this parameter will be
2041                    // seen by startPreview from onResume()
2042                    mEffectUriFromGallery = data.getData().toString();
2043                    Log.v(TAG, "Received URI from gallery: " + mEffectUriFromGallery);
2044                    mResetEffect = false;
2045                } else {
2046                    mEffectUriFromGallery = null;
2047                    Log.w(TAG, "No URI from gallery");
2048                    mResetEffect = true;
2049                }
2050                break;
2051        }
2052    }
2053
2054    @Override
2055    public void onEffectsUpdate(int effectId, int effectMsg) {
2056        Log.v(TAG, "onEffectsUpdate. Effect Message = " + effectMsg);
2057        if (effectMsg == EffectsRecorder.EFFECT_MSG_EFFECTS_STOPPED) {
2058            // Effects have shut down. Hide learning message if any,
2059            // and restart regular preview.
2060            mBgLearningMessageFrame.setVisibility(View.GONE);
2061            checkQualityAndStartPreview();
2062        } else if (effectMsg == EffectsRecorder.EFFECT_MSG_RECORDING_DONE) {
2063            // This follows the codepath from onStopVideoRecording.
2064            if (mEffectsDisplayResult && !addVideoToMediaStore()) {
2065                if (mIsVideoCaptureIntent) {
2066                    if (mQuickCapture) {
2067                        doReturnToCaller(true);
2068                    } else {
2069                        showAlert();
2070                    }
2071                } else {
2072                    getThumbnail();
2073                }
2074            }
2075            mEffectsDisplayResult = false;
2076            // In onPause, these were not called if the effects were active. We
2077            // had to wait till the effects recording is complete to do this.
2078            if (mPaused) {
2079                closeVideoFileDescriptor();
2080                clearVideoNamer();
2081            }
2082        } else if (effectMsg == EffectsRecorder.EFFECT_MSG_PREVIEW_RUNNING) {
2083            // Enable the shutter button once the preview is complete.
2084            mShutterButton.setEnabled(true);
2085        } else if (effectId == EffectsRecorder.EFFECT_BACKDROPPER) {
2086            switch (effectMsg) {
2087                case EffectsRecorder.EFFECT_MSG_STARTED_LEARNING:
2088                    mBgLearningMessageFrame.setVisibility(View.VISIBLE);
2089                    break;
2090                case EffectsRecorder.EFFECT_MSG_DONE_LEARNING:
2091                case EffectsRecorder.EFFECT_MSG_SWITCHING_EFFECT:
2092                    mBgLearningMessageFrame.setVisibility(View.GONE);
2093                    break;
2094            }
2095        }
2096        // In onPause, this was not called if the effects were active. We had to
2097        // wait till the effects completed to do this.
2098        if (mPaused) {
2099            Log.v(TAG, "OnEffectsUpdate: closing effects if activity paused");
2100            closeEffects();
2101        }
2102    }
2103
2104    public void onCancelBgTraining(View v) {
2105        // Remove training message
2106        mBgLearningMessageFrame.setVisibility(View.GONE);
2107        // Write default effect out to shared prefs
2108        writeDefaultEffectToPrefs();
2109        // Tell the indicator controller to redraw based on new shared pref values
2110//        mIndicatorControlContainer.reloadPreferences();
2111        // Tell VideoCamer to re-init based on new shared pref values.
2112        onSharedPreferenceChanged();
2113    }
2114
2115    @Override
2116    public synchronized void onEffectsError(Exception exception, String fileName) {
2117        // TODO: Eventually we may want to show the user an error dialog, and then restart the
2118        // camera and encoder gracefully. For now, we just delete the file and bail out.
2119        if (fileName != null && new File(fileName).exists()) {
2120            deleteVideoFile(fileName);
2121        }
2122        try {
2123            if (Class.forName("android.filterpacks.videosink.MediaRecorderStopException")
2124                    .isInstance(exception)) {
2125                Log.w(TAG, "Problem recoding video file. Removing incomplete file.");
2126                return;
2127            }
2128        } catch (ClassNotFoundException ex) {
2129            Log.w(TAG, ex);
2130        }
2131        throw new RuntimeException("Error during recording!", exception);
2132    }
2133
2134    private void initializeControlByIntent() {
2135        if (mIsVideoCaptureIntent) {
2136            mActivity.hideSwitcher();
2137            // Cannot use RotateImageView for "done" and "cancel" button because
2138            // the tablet layout uses RotateLayout, which cannot be cast to
2139            // RotateImageView.
2140            mReviewDoneButton = (Rotatable) mRootView.findViewById(R.id.btn_done);
2141            mReviewCancelButton = (Rotatable) mRootView.findViewById(R.id.btn_cancel);
2142            mReviewPlayButton = (RotateImageView) mRootView.findViewById(R.id.btn_play);
2143
2144            ((View) mReviewCancelButton).setVisibility(View.VISIBLE);
2145
2146            ((View) mReviewDoneButton).setOnClickListener(new OnClickListener() {
2147                @Override
2148                public void onClick(View v) {
2149                    onReviewDoneClicked(v);
2150                }
2151            });
2152            ((View) mReviewCancelButton).setOnClickListener(new OnClickListener() {
2153                @Override
2154                public void onClick(View v) {
2155                    onReviewCancelClicked(v);
2156                }
2157            });
2158
2159            ((View) mReviewPlayButton).setOnClickListener(new OnClickListener() {
2160                @Override
2161                public void onClick(View v) {
2162                    onReviewPlayClicked(v);
2163                }
2164            });
2165
2166
2167            // Not grayed out upon disabled, to make the follow-up fade-out
2168            // effect look smooth. Note that the review done button in tablet
2169            // layout is not a TwoStateImageView.
2170            if (mReviewDoneButton instanceof TwoStateImageView) {
2171                ((TwoStateImageView) mReviewDoneButton).enableFilter(false);
2172            }
2173        } else {
2174            mActivity.mThumbnailView = (RotateImageView) mRootView.findViewById(R.id.thumbnail);
2175            if (mActivity.mThumbnailView != null) {
2176                mActivity.mThumbnailView.enableFilter(false);
2177                mActivity.mThumbnailView.setVisibility(View.VISIBLE);
2178                mActivity.mThumbnailViewWidth = mActivity.mThumbnailView.getLayoutParams().width;
2179            }
2180        }
2181    }
2182
2183    private void initializeMiscControls() {
2184        mPreviewFrameLayout = (PreviewFrameLayout) mRootView.findViewById(R.id.frame);
2185        mPreviewFrameLayout.setOnLayoutChangeListener(mActivity);
2186        mReviewImage = (ImageView) mRootView.findViewById(R.id.review_image);
2187
2188        mShutterButton = mActivity.getShutterButton();
2189        mShutterButton.setImageResource(R.drawable.btn_new_shutter_video);
2190        mShutterButton.setOnShutterButtonListener(this);
2191        mShutterButton.requestFocus();
2192
2193        // Disable the shutter button if effects are ON since it might take
2194        // a little more time for the effects preview to be ready. We do not
2195        // want to allow recording before that happens. The shutter button
2196        // will be enabled when we get the message from effectsrecorder that
2197        // the preview is running. This becomes critical when the camera is
2198        // swapped.
2199        if (effectsActive()) {
2200            mShutterButton.setEnabled(false);
2201        }
2202
2203        mRecordingTimeView = (TextView) mRootView.findViewById(R.id.recording_time);
2204        mRecordingTimeRect = (RotateLayout) mRootView.findViewById(R.id.recording_time_rect);
2205        mTimeLapseLabel = mRootView.findViewById(R.id.time_lapse_label);
2206        // The R.id.labels can only be found in phone layout.
2207        // That is, mLabelsLinearLayout should be null in tablet layout.
2208        mLabelsLinearLayout = (LinearLayout) mRootView.findViewById(R.id.labels);
2209
2210        mBgLearningMessageRotater = (RotateLayout) mRootView.findViewById(R.id.bg_replace_message);
2211        mBgLearningMessageFrame = mRootView.findViewById(R.id.bg_replace_message_frame);
2212    }
2213
2214    @Override
2215    public void onConfigurationChanged(Configuration newConfig) {
2216        setDisplayOrientation();
2217
2218        // Change layout in response to configuration change
2219        LayoutInflater inflater = mActivity.getLayoutInflater();
2220        ((ViewGroup) mRootView).removeAllViews();
2221        inflater.inflate(R.layout.video_module, (ViewGroup) mRootView);
2222
2223        // from onCreate()
2224        initializeOverlay();
2225        initializeControlByIntent();
2226        initializeSurfaceView();
2227        initializeMiscControls();
2228        showTimeLapseUI(mCaptureTimeLapse);
2229        initializeVideoSnapshot();
2230        resizeForPreviewAspectRatio();
2231        initializeVideoControl();
2232
2233        // from onResume()
2234        showVideoSnapshotUI(false);
2235        initializeZoom();
2236        if (!mIsVideoCaptureIntent) {
2237            mActivity.updateThumbnailView();
2238        }
2239    }
2240
2241    @Override
2242    public void onOverriddenPreferencesClicked() {
2243    }
2244
2245    @Override
2246    public void onRestorePreferencesClicked() {
2247        Runnable runnable = new Runnable() {
2248            @Override
2249            public void run() {
2250                restorePreferences();
2251            }
2252        };
2253        mRotateDialog.showAlertDialog(
2254                null,
2255                mActivity.getString(R.string.confirm_restore_message),
2256                mActivity.getString(android.R.string.ok), runnable,
2257                mActivity.getString(android.R.string.cancel), null);
2258    }
2259
2260    private void restorePreferences() {
2261        // Reset the zoom. Zoom value is not stored in preference.
2262        if (mParameters.isZoomSupported()) {
2263            mZoomValue = 0;
2264            setCameraParameters();
2265//            mZoomControl.setZoomIndex(0);
2266        }
2267
2268//        if (mIndicatorControlContainer != null) {
2269//            mIndicatorControlContainer.dismissSettingPopup();
2270            CameraSettings.restorePreferences(mActivity, mPreferences,
2271                    mParameters);
2272//            mIndicatorControlContainer.reloadPreferences();
2273            onSharedPreferenceChanged();
2274//        }
2275    }
2276
2277    private boolean effectsActive() {
2278        return (mEffectType != EffectsRecorder.EFFECT_NONE);
2279    }
2280
2281    @Override
2282    public void onSharedPreferenceChanged() {
2283        // ignore the events after "onPause()" or preview has not started yet
2284        if (mPaused) return;
2285        synchronized (mPreferences) {
2286            // If mCameraDevice is not ready then we can set the parameter in
2287            // startPreview().
2288            if (mActivity.mCameraDevice == null) return;
2289
2290            boolean recordLocation = RecordLocationPreference.get(
2291                    mPreferences, mContentResolver);
2292            mLocationManager.recordLocation(recordLocation);
2293
2294            // Check if the current effects selection has changed
2295            if (updateEffectSelection()) return;
2296
2297            readVideoPreferences();
2298            showTimeLapseUI(mCaptureTimeLapse);
2299            // We need to restart the preview if preview size is changed.
2300            Size size = mParameters.getPreviewSize();
2301            if (size.width != mDesiredPreviewWidth
2302                    || size.height != mDesiredPreviewHeight) {
2303                if (!effectsActive()) {
2304                    stopPreview();
2305                } else {
2306                    mEffectsRecorder.release();
2307                    mEffectsRecorder = null;
2308                }
2309                resizeForPreviewAspectRatio();
2310                startPreview(); // Parameters will be set in startPreview().
2311            } else {
2312                setCameraParameters();
2313            }
2314        }
2315    }
2316
2317    private void switchCamera() {
2318        if (mPaused) return;
2319
2320        Log.d(TAG, "Start to switch camera.");
2321        mCameraId = mPendingSwitchCameraId;
2322        mPendingSwitchCameraId = -1;
2323        mVideoControl.setCameraId(mCameraId);
2324
2325        closeCamera();
2326
2327        // Restart the camera and initialize the UI. From onCreate.
2328        mPreferences.setLocalId(mActivity, mCameraId);
2329        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2330        CameraOpenThread cameraOpenThread = new CameraOpenThread();
2331        cameraOpenThread.start();
2332        try {
2333            cameraOpenThread.join();
2334        } catch (InterruptedException ex) {
2335            // ignore
2336        }
2337        readVideoPreferences();
2338        startPreview();
2339        initializeVideoSnapshot();
2340        resizeForPreviewAspectRatio();
2341        initializeVideoControl();
2342
2343        // From onResume
2344        initializeZoom();
2345        setOrientationIndicator(mOrientationCompensation, false);
2346
2347        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2348            // Start switch camera animation. Post a message because
2349            // onFrameAvailable from the old camera may already exist.
2350            mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
2351        }
2352    }
2353
2354    // Preview texture has been copied. Now camera can be released and the
2355    // animation can be started.
2356    @Override
2357    public void onPreviewTextureCopied() {
2358        mHandler.sendEmptyMessage(SWITCH_CAMERA);
2359    }
2360
2361    private boolean updateEffectSelection() {
2362        int previousEffectType = mEffectType;
2363        Object previousEffectParameter = mEffectParameter;
2364        mEffectType = CameraSettings.readEffectType(mPreferences);
2365        mEffectParameter = CameraSettings.readEffectParameter(mPreferences);
2366
2367        if (mEffectType == previousEffectType) {
2368            if (mEffectType == EffectsRecorder.EFFECT_NONE) return false;
2369            if (mEffectParameter.equals(previousEffectParameter)) return false;
2370        }
2371        Log.v(TAG, "New effect selection: " + mPreferences.getString(
2372                CameraSettings.KEY_VIDEO_EFFECT, "none"));
2373
2374        if (mEffectType == EffectsRecorder.EFFECT_NONE) {
2375            // Stop effects and return to normal preview
2376            mEffectsRecorder.stopPreview();
2377            mPreviewing = false;
2378            return true;
2379        }
2380        if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER &&
2381            ((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) {
2382            // Request video from gallery to use for background
2383            Intent i = new Intent(Intent.ACTION_PICK);
2384            i.setDataAndType(Video.Media.EXTERNAL_CONTENT_URI,
2385                             "video/*");
2386            i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
2387            mActivity.startActivityForResult(i, REQUEST_EFFECT_BACKDROPPER);
2388            return true;
2389        }
2390        if (previousEffectType == EffectsRecorder.EFFECT_NONE) {
2391            // Stop regular preview and start effects.
2392            stopPreview();
2393            checkQualityAndStartPreview();
2394        } else {
2395            // Switch currently running effect
2396            mEffectsRecorder.setEffect(mEffectType, mEffectParameter);
2397        }
2398        return true;
2399    }
2400
2401    // Verifies that the current preview view size is correct before starting
2402    // preview. If not, resets the surface texture and resizes the view.
2403    private void checkQualityAndStartPreview() {
2404        readVideoPreferences();
2405        showTimeLapseUI(mCaptureTimeLapse);
2406        Size size = mParameters.getPreviewSize();
2407        if (size.width != mDesiredPreviewWidth
2408                || size.height != mDesiredPreviewHeight) {
2409            resizeForPreviewAspectRatio();
2410        }
2411        // Start up preview again
2412        startPreview();
2413    }
2414
2415    private void showTimeLapseUI(boolean enable) {
2416        if (mTimeLapseLabel != null) {
2417            mTimeLapseLabel.setVisibility(enable ? View.VISIBLE : View.GONE);
2418        }
2419    }
2420
2421    @Override
2422    public boolean dispatchTouchEvent(MotionEvent m) {
2423        if (mSwitchingCamera) return true;
2424        if (mPopup == null && mRenderOverlay != null && mControlEnabled) {
2425            mRenderOverlay.directDispatchTouch(m);
2426        }
2427        return false;
2428    }
2429
2430    private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener {
2431        @Override
2432        public void onZoomValueChanged(int index) {
2433            // Not useful to change zoom value when the activity is paused.
2434            if (mPaused) return;
2435
2436            mZoomValue = index;
2437
2438            // Set zoom parameters asynchronously
2439            mParameters.setZoom(mZoomValue);
2440            mActivity.mCameraDevice.setParametersAsync(mParameters);
2441        }
2442    }
2443
2444    private void initializeZoom() {
2445        if (!mParameters.isZoomSupported()) return;
2446
2447        mZoomMax = mParameters.getMaxZoom();
2448        // Currently we use immediate zoom for fast zooming to get better UX and
2449        // there is no plan to take advantage of the smooth zoom.
2450    }
2451
2452    private void initializeVideoSnapshot() {
2453        if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
2454            mActivity.setSingleTapUpListener(mPreviewFrameLayout);
2455            // Show the tap to focus toast if this is the first start.
2456            if (mPreferences.getBoolean(
2457                        CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, true)) {
2458                // Delay the toast for one second to wait for orientation.
2459                mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_SNAPSHOT_TOAST, 1000);
2460            }
2461        } else {
2462            mActivity.setSingleTapUpListener(null);
2463        }
2464    }
2465
2466    void showVideoSnapshotUI(boolean enabled) {
2467        if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
2468            mPreviewFrameLayout.showBorder(enabled);
2469//            mIndicatorControlContainer.enableZoom(!enabled);
2470            mShutterButton.setEnabled(!enabled);
2471        }
2472    }
2473
2474    // Preview area is touched. Take a picture.
2475    @Override
2476    public void onSingleTapUp(View view, int x, int y) {
2477        if (mMediaRecorderRecording && effectsActive()) {
2478            new RotateTextToast(mActivity, R.string.disable_video_snapshot_hint,
2479                    mOrientation).show();
2480            return;
2481        }
2482
2483        if (mPaused || mSnapshotInProgress || effectsActive()) {
2484            return;
2485        }
2486
2487        if (!mMediaRecorderRecording)
2488        {
2489            // check for dismissing popup
2490            if (mPopup != null)
2491                dismissPopup();
2492            return;
2493        }
2494
2495        // Set rotation and gps data.
2496        int rotation = Util.getJpegRotation(mCameraId, mOrientation);
2497        mParameters.setRotation(rotation);
2498        Location loc = mLocationManager.getCurrentLocation();
2499        Util.setGpsParameters(mParameters, loc);
2500        mActivity.mCameraDevice.setParameters(mParameters);
2501
2502        Log.v(TAG, "Video snapshot start");
2503        mActivity.mCameraDevice.takePicture(null, null, null, new JpegPictureCallback(loc));
2504        showVideoSnapshotUI(true);
2505        mSnapshotInProgress = true;
2506    }
2507
2508    @Override
2509    public void updateCameraAppView() {
2510        if (!mPreviewing || mParameters.getFlashMode() == null) return;
2511
2512        // When going to and back from gallery, we need to turn off/on the flash.
2513        if (!mActivity.mShowCameraAppView) {
2514            if (mParameters.getFlashMode().equals(Parameters.FLASH_MODE_OFF)) {
2515                mRestoreFlash = false;
2516                return;
2517            }
2518            mRestoreFlash = true;
2519            setCameraParameters();
2520        } else if (mRestoreFlash) {
2521            mRestoreFlash = false;
2522            setCameraParameters();
2523        }
2524    }
2525
2526    @Override
2527    public void onFullScreenChanged(boolean full) {
2528        if (ApiHelper.HAS_SURFACE_TEXTURE) return;
2529
2530        if (full) {
2531            mPreviewSurfaceView.expand();
2532        } else {
2533            mPreviewSurfaceView.shrink();
2534        }
2535    }
2536
2537    private final class JpegPictureCallback implements PictureCallback {
2538        Location mLocation;
2539
2540        public JpegPictureCallback(Location loc) {
2541            mLocation = loc;
2542        }
2543
2544        @Override
2545        public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) {
2546            Log.v(TAG, "onPictureTaken");
2547            mSnapshotInProgress = false;
2548            showVideoSnapshotUI(false);
2549            storeImage(jpegData, mLocation);
2550        }
2551    }
2552
2553    private void storeImage(final byte[] data, Location loc) {
2554        long dateTaken = System.currentTimeMillis();
2555        String title = Util.createJpegName(dateTaken);
2556        int orientation = Exif.getOrientation(data);
2557        Size s = mParameters.getPictureSize();
2558        Uri uri = Storage.addImage(mContentResolver, title, dateTaken, loc, orientation, data,
2559                s.width, s.height);
2560        if (uri != null) {
2561            // Create a thumbnail whose width is equal or bigger than that of the preview.
2562            int ratio = (int) Math.ceil((double) mParameters.getPictureSize().width
2563                    / mPreviewFrameLayout.getWidth());
2564            int inSampleSize = Integer.highestOneBit(ratio);
2565            mActivity.mThumbnail = Thumbnail.createThumbnail(data, orientation, inSampleSize, uri);
2566            if (mActivity.mThumbnail != null && mActivity.mThumbnailView != null) {
2567                mActivity.mThumbnailView.setBitmap(mActivity.mThumbnail.getBitmap());
2568            }
2569            Util.broadcastNewPicture(mActivity, uri);
2570        }
2571    }
2572
2573    private boolean resetEffect() {
2574        if (mResetEffect) {
2575            String value = mPreferences.getString(CameraSettings.KEY_VIDEO_EFFECT,
2576                    mPrefVideoEffectDefault);
2577            if (!mPrefVideoEffectDefault.equals(value)) {
2578                writeDefaultEffectToPrefs();
2579                return true;
2580            }
2581        }
2582        mResetEffect = true;
2583        return false;
2584    }
2585
2586    private String convertOutputFormatToMimeType(int outputFileFormat) {
2587        if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
2588            return "video/mp4";
2589        }
2590        return "video/3gpp";
2591    }
2592
2593    private String convertOutputFormatToFileExt(int outputFileFormat) {
2594        if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
2595            return ".mp4";
2596        }
2597        return ".3gp";
2598    }
2599
2600    private void closeVideoFileDescriptor() {
2601        if (mVideoFileDescriptor != null) {
2602            try {
2603                mVideoFileDescriptor.close();
2604            } catch (IOException e) {
2605                Log.e(TAG, "Fail to close fd", e);
2606            }
2607            mVideoFileDescriptor = null;
2608        }
2609    }
2610
2611    private void showTapToSnapshotToast() {
2612        new RotateTextToast(mActivity, R.string.video_snapshot_hint, mOrientationCompensation)
2613                .show();
2614        // Clear the preference.
2615        Editor editor = mPreferences.edit();
2616        editor.putBoolean(CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, false);
2617        editor.apply();
2618    }
2619
2620    private void clearVideoNamer() {
2621        if (mVideoNamer != null) {
2622            mVideoNamer.finish();
2623            mVideoNamer = null;
2624        }
2625    }
2626
2627    private static class VideoNamer extends Thread {
2628        private boolean mRequestPending;
2629        private ContentResolver mResolver;
2630        private ContentValues mValues;
2631        private boolean mStop;
2632        private Uri mUri;
2633
2634        // Runs in main thread
2635        public VideoNamer() {
2636            start();
2637        }
2638
2639        // Runs in main thread
2640        public synchronized void prepareUri(
2641                ContentResolver resolver, ContentValues values) {
2642            mRequestPending = true;
2643            mResolver = resolver;
2644            mValues = new ContentValues(values);
2645            notifyAll();
2646        }
2647
2648        // Runs in main thread
2649        public synchronized Uri getUri() {
2650            // wait until the request is done.
2651            while (mRequestPending) {
2652                try {
2653                    wait();
2654                } catch (InterruptedException ex) {
2655                    // ignore.
2656                }
2657            }
2658            Uri uri = mUri;
2659            mUri = null;
2660            return uri;
2661        }
2662
2663        // Runs in namer thread
2664        @Override
2665        public synchronized void run() {
2666            while (true) {
2667                if (mStop) break;
2668                if (!mRequestPending) {
2669                    try {
2670                        wait();
2671                    } catch (InterruptedException ex) {
2672                        // ignore.
2673                    }
2674                    continue;
2675                }
2676                cleanOldUri();
2677                generateUri();
2678                mRequestPending = false;
2679                notifyAll();
2680            }
2681            cleanOldUri();
2682        }
2683
2684        // Runs in main thread
2685        public synchronized void finish() {
2686            mStop = true;
2687            notifyAll();
2688        }
2689
2690        // Runs in namer thread
2691        private void generateUri() {
2692            Uri videoTable = Uri.parse("content://media/external/video/media");
2693            mUri = mResolver.insert(videoTable, mValues);
2694        }
2695
2696        // Runs in namer thread
2697        private void cleanOldUri() {
2698            if (mUri == null) return;
2699            mResolver.delete(mUri, null, null);
2700            mUri = null;
2701        }
2702    }
2703
2704    private class SurfaceViewCallback implements SurfaceHolder.Callback {
2705        public SurfaceViewCallback() {}
2706
2707        @Override
2708        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
2709            Log.v(TAG, "Surface changed. width=" + width + ". height=" + height);
2710        }
2711
2712        @Override
2713        public void surfaceCreated(SurfaceHolder holder) {
2714            Log.v(TAG, "Surface created");
2715            mSurfaceViewReady = true;
2716            if (mPaused) return;
2717            if (!ApiHelper.HAS_SURFACE_TEXTURE) {
2718                mActivity.mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder());
2719                if (!mPreviewing) {
2720                    startPreview();
2721                }
2722            }
2723        }
2724
2725        @Override
2726        public void surfaceDestroyed(SurfaceHolder holder) {
2727            Log.v(TAG, "Surface destroyed");
2728            mSurfaceViewReady = false;
2729            if (mPaused) return;
2730            if (!ApiHelper.HAS_SURFACE_TEXTURE) {
2731                stopVideoRecording();
2732                stopPreview();
2733            }
2734        }
2735    }
2736
2737    @Override
2738    public boolean updateStorageHintOnResume() {
2739        return true;
2740    }
2741
2742    // required by OnPreferenceChangedListener
2743    @Override
2744    public void onCameraPickerClicked(int cameraId) {
2745        if (mPaused || mPendingSwitchCameraId != -1) return;
2746
2747        mPendingSwitchCameraId = cameraId;
2748        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2749            Log.d(TAG, "Start to copy texture.");
2750            // We need to keep a preview frame for the animation before
2751            // releasing the camera. This will trigger onPreviewTextureCopied.
2752            ((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
2753            // Disable all camera controls.
2754            mSwitchingCamera = true;
2755        } else {
2756            switchCamera();
2757        }
2758    }
2759
2760    @Override
2761    public boolean needsSwitcher() {
2762        return !mIsVideoCaptureIntent;
2763    }
2764
2765    @Override
2766    public void onPieOpened(int centerX, int centerY) {
2767        mActivity.cancelActivityTouchHandling();
2768        mActivity.setSwipingEnabled(false);
2769    }
2770
2771    @Override
2772    public void onPieClosed() {
2773        mActivity.setSwipingEnabled(true);
2774    }
2775
2776    public void showPopup(AbstractSettingPopup popup) {
2777        mActivity.hideUI();
2778        mPopup = popup;
2779        mPopup.setVisibility(View.VISIBLE);
2780        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
2781                LayoutParams.WRAP_CONTENT);
2782        lp.gravity = Gravity.CENTER;
2783        ((FrameLayout) mRootView).addView(mPopup, lp);
2784    }
2785
2786    public void dismissPopup() {
2787        mActivity.showUI();
2788        if (mPopup != null) {
2789            ((FrameLayout) mRootView).removeView(mPopup);
2790            mPopup = null;
2791        }
2792    }
2793
2794
2795}
2796