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