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