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