VideoModule.java revision 46b602f080aaf39a365962c69ea39b917cce248e
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
1599        mActivity.updateStorageSpaceAndHint();
1600        if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
1601            Log.v(TAG, "Storage issue, ignore the start request");
1602            return;
1603        }
1604
1605        mCurrentVideoUri = null;
1606        if (effectsActive()) {
1607            initializeEffectsRecording();
1608            if (mEffectsRecorder == null) {
1609                Log.e(TAG, "Fail to initialize effect recorder");
1610                return;
1611            }
1612        } else {
1613            initializeRecorder();
1614            if (mMediaRecorder == null) {
1615                Log.e(TAG, "Fail to initialize media recorder");
1616                return;
1617            }
1618        }
1619
1620        pauseAudioPlayback();
1621
1622        if (effectsActive()) {
1623            try {
1624                mEffectsRecorder.startRecording();
1625            } catch (RuntimeException e) {
1626                Log.e(TAG, "Could not start effects recorder. ", e);
1627                releaseEffectsRecorder();
1628                return;
1629            }
1630        } else {
1631            try {
1632                mMediaRecorder.start(); // Recording is now started
1633            } catch (RuntimeException e) {
1634                Log.e(TAG, "Could not start media recorder. ", e);
1635                releaseMediaRecorder();
1636                // If start fails, frameworks will not lock the camera for us.
1637                mActivity.mCameraDevice.lock();
1638                return;
1639            }
1640        }
1641
1642        // The parameters may have been changed by MediaRecorder upon starting
1643        // recording. We need to alter the parameters if we support camcorder
1644        // zoom. To reduce latency when setting the parameters during zoom, we
1645        // update mParameters here once.
1646        if (ApiHelper.HAS_ZOOM_WHEN_RECORDING) {
1647            mParameters = mActivity.mCameraDevice.getParameters();
1648        }
1649
1650        enableCameraControls(false);
1651
1652        mMediaRecorderRecording = true;
1653        mRecordingStartTime = SystemClock.uptimeMillis();
1654        showRecordingUI(true);
1655
1656        updateRecordingTime();
1657        keepScreenOn();
1658    }
1659
1660    private void showRecordingUI(boolean recording) {
1661        if (recording) {
1662            mShutterButton.setImageResource(R.drawable.btn_shutter_video_recording);
1663            mActivity.hideSwitcher();
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_new_shutter_video);
1683            mActivity.showSwitcher();
1684            mRecordingTimeView.setVisibility(View.GONE);
1685            if (mReviewControl != null) mReviewControl.setVisibility(View.VISIBLE);
1686            if (mCaptureTimeLapse) {
1687//                mIndicatorControlContainer.stopTimeLapseAnimation();
1688            }
1689            if (!ApiHelper.HAS_ZOOM_WHEN_RECORDING
1690                    && mParameters.isZoomSupported()) {
1691//                mZoomControl.setVisibility(View.VISIBLE);
1692            }
1693        }
1694    }
1695
1696    private void showAlert() {
1697        Bitmap bitmap = null;
1698        if (mVideoFileDescriptor != null) {
1699            bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
1700                    mPreviewFrameLayout.getWidth());
1701        } else if (mCurrentVideoFilename != null) {
1702            bitmap = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename,
1703                    mPreviewFrameLayout.getWidth());
1704        }
1705        if (bitmap != null) {
1706            // MetadataRetriever already rotates the thumbnail. We should rotate
1707            // it to match the UI orientation (and mirror if it is front-facing camera).
1708            CameraInfo[] info = CameraHolder.instance().getCameraInfo();
1709            boolean mirror = (info[mCameraId].facing == CameraInfo.CAMERA_FACING_FRONT);
1710            bitmap = Util.rotateAndMirror(bitmap, -mOrientationCompensationAtRecordStart,
1711                    mirror);
1712            mReviewImage.setImageBitmap(bitmap);
1713            mReviewImage.setVisibility(View.VISIBLE);
1714        }
1715
1716        Util.fadeOut(mShutterButton);
1717
1718        Util.fadeIn((View) mReviewDoneButton);
1719        Util.fadeIn(mReviewPlayButton);
1720        enableCameraControls(false);
1721
1722        showTimeLapseUI(false);
1723    }
1724
1725    private void hideAlert() {
1726        mReviewImage.setVisibility(View.GONE);
1727        mShutterButton.setEnabled(true);
1728        enableCameraControls(true);
1729
1730        Util.fadeOut((View) mReviewDoneButton);
1731        Util.fadeOut(mReviewPlayButton);
1732
1733        Util.fadeIn(mShutterButton);
1734
1735        if (mCaptureTimeLapse) {
1736            showTimeLapseUI(true);
1737        }
1738    }
1739
1740    private boolean stopVideoRecording() {
1741        Log.v(TAG, "stopVideoRecording");
1742        mActivity.setSwipingEnabled(true);
1743        mActivity.showSwitcher();
1744
1745        boolean fail = false;
1746        if (mMediaRecorderRecording) {
1747            boolean shouldAddToMediaStoreNow = false;
1748
1749            try {
1750                if (effectsActive()) {
1751                    // This is asynchronous, so we can't add to media store now because thumbnail
1752                    // may not be ready. In such case addVideoToMediaStore is called later
1753                    // through a callback from the MediaEncoderFilter to EffectsRecorder,
1754                    // and then to the VideoCamera.
1755                    mEffectsRecorder.stopRecording();
1756                } else {
1757                    mMediaRecorder.setOnErrorListener(null);
1758                    mMediaRecorder.setOnInfoListener(null);
1759                    mMediaRecorder.stop();
1760                    shouldAddToMediaStoreNow = true;
1761                }
1762                mCurrentVideoFilename = mVideoFilename;
1763                Log.v(TAG, "stopVideoRecording: Setting current video filename: "
1764                        + mCurrentVideoFilename);
1765            } catch (RuntimeException e) {
1766                Log.e(TAG, "stop fail",  e);
1767                if (mVideoFilename != null) deleteVideoFile(mVideoFilename);
1768                fail = true;
1769            }
1770            mMediaRecorderRecording = false;
1771
1772            // If the activity is paused, this means activity is interrupted
1773            // during recording. Release the camera as soon as possible because
1774            // face unlock or other applications may need to use the camera.
1775            // However, if the effects are active, then we can only release the
1776            // camera and cannot release the effects recorder since that will
1777            // stop the graph. It is possible to separate out the Camera release
1778            // part and the effects release part. However, the effects recorder
1779            // does hold on to the camera, hence, it needs to be "disconnected"
1780            // from the camera in the closeCamera call.
1781            if (mPaused) {
1782                // Closing only the camera part if effects active. Effects will
1783                // be closed in the callback from effects.
1784                boolean closeEffects = !effectsActive();
1785                closeCamera(closeEffects);
1786            }
1787
1788            showRecordingUI(false);
1789            if (!mIsVideoCaptureIntent) {
1790                enableCameraControls(true);
1791            }
1792            // The orientation was fixed during video recording. Now make it
1793            // reflect the device orientation as video recording is stopped.
1794            setOrientationIndicator(mOrientationCompensation, true);
1795            keepScreenOnAwhile();
1796            if (shouldAddToMediaStoreNow) {
1797                if (addVideoToMediaStore()) fail = true;
1798            }
1799        }
1800        // always release media recorder if no effects running
1801        if (!effectsActive()) {
1802            releaseMediaRecorder();
1803            if (!mPaused) {
1804                mActivity.mCameraDevice.lock();
1805                if (ApiHelper.HAS_SURFACE_TEXTURE &&
1806                    !ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
1807                    stopPreview();
1808                    // Switch back to use SurfaceTexture for preview.
1809                    ((CameraScreenNail) mActivity.mCameraScreenNail).setOneTimeOnFrameDrawnListener(
1810                            mFrameDrawnListener);
1811                    startPreview();
1812                }
1813            }
1814        }
1815        // Update the parameters here because the parameters might have been altered
1816        // by MediaRecorder.
1817        if (!mPaused) mParameters = mActivity.mCameraDevice.getParameters();
1818        return fail;
1819    }
1820
1821    private void resetScreenOn() {
1822        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1823        mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1824    }
1825
1826    private void keepScreenOnAwhile() {
1827        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1828        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1829        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1830    }
1831
1832    private void keepScreenOn() {
1833        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1834        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1835    }
1836
1837    private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
1838        long seconds = milliSeconds / 1000; // round down to compute seconds
1839        long minutes = seconds / 60;
1840        long hours = minutes / 60;
1841        long remainderMinutes = minutes - (hours * 60);
1842        long remainderSeconds = seconds - (minutes * 60);
1843
1844        StringBuilder timeStringBuilder = new StringBuilder();
1845
1846        // Hours
1847        if (hours > 0) {
1848            if (hours < 10) {
1849                timeStringBuilder.append('0');
1850            }
1851            timeStringBuilder.append(hours);
1852
1853            timeStringBuilder.append(':');
1854        }
1855
1856        // Minutes
1857        if (remainderMinutes < 10) {
1858            timeStringBuilder.append('0');
1859        }
1860        timeStringBuilder.append(remainderMinutes);
1861        timeStringBuilder.append(':');
1862
1863        // Seconds
1864        if (remainderSeconds < 10) {
1865            timeStringBuilder.append('0');
1866        }
1867        timeStringBuilder.append(remainderSeconds);
1868
1869        // Centi seconds
1870        if (displayCentiSeconds) {
1871            timeStringBuilder.append('.');
1872            long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
1873            if (remainderCentiSeconds < 10) {
1874                timeStringBuilder.append('0');
1875            }
1876            timeStringBuilder.append(remainderCentiSeconds);
1877        }
1878
1879        return timeStringBuilder.toString();
1880    }
1881
1882    private long getTimeLapseVideoLength(long deltaMs) {
1883        // For better approximation calculate fractional number of frames captured.
1884        // This will update the video time at a higher resolution.
1885        double numberOfFrames = (double) deltaMs / mTimeBetweenTimeLapseFrameCaptureMs;
1886        return (long) (numberOfFrames / mProfile.videoFrameRate * 1000);
1887    }
1888
1889    private void updateRecordingTime() {
1890        if (!mMediaRecorderRecording) {
1891            return;
1892        }
1893        long now = SystemClock.uptimeMillis();
1894        long delta = now - mRecordingStartTime;
1895
1896        // Starting a minute before reaching the max duration
1897        // limit, we'll countdown the remaining time instead.
1898        boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
1899                && delta >= mMaxVideoDurationInMs - 60000);
1900
1901        long deltaAdjusted = delta;
1902        if (countdownRemainingTime) {
1903            deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
1904        }
1905        String text;
1906
1907        long targetNextUpdateDelay;
1908        if (!mCaptureTimeLapse) {
1909            text = millisecondToTimeString(deltaAdjusted, false);
1910            targetNextUpdateDelay = 1000;
1911        } else {
1912            // The length of time lapse video is different from the length
1913            // of the actual wall clock time elapsed. Display the video length
1914            // only in format hh:mm:ss.dd, where dd are the centi seconds.
1915            text = millisecondToTimeString(getTimeLapseVideoLength(delta), true);
1916            targetNextUpdateDelay = mTimeBetweenTimeLapseFrameCaptureMs;
1917        }
1918
1919        mRecordingTimeView.setText(text);
1920
1921        if (mRecordingTimeCountsDown != countdownRemainingTime) {
1922            // Avoid setting the color on every update, do it only
1923            // when it needs changing.
1924            mRecordingTimeCountsDown = countdownRemainingTime;
1925
1926            int color = mActivity.getResources().getColor(countdownRemainingTime
1927                    ? R.color.recording_time_remaining_text
1928                    : R.color.recording_time_elapsed_text);
1929
1930            mRecordingTimeView.setTextColor(color);
1931        }
1932
1933        long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
1934        mHandler.sendEmptyMessageDelayed(
1935                UPDATE_RECORD_TIME, actualNextUpdateDelay);
1936    }
1937
1938    private static boolean isSupported(String value, List<String> supported) {
1939        return supported == null ? false : supported.indexOf(value) >= 0;
1940    }
1941
1942    @SuppressWarnings("deprecation")
1943    private void setCameraParameters() {
1944        mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
1945        mParameters.setPreviewFrameRate(mProfile.videoFrameRate);
1946
1947        // Set flash mode.
1948        String flashMode;
1949        if (mActivity.mShowCameraAppView) {
1950            flashMode = mPreferences.getString(
1951                    CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE,
1952                    mActivity.getString(R.string.pref_camera_video_flashmode_default));
1953        } else {
1954            flashMode = Parameters.FLASH_MODE_OFF;
1955        }
1956        List<String> supportedFlash = mParameters.getSupportedFlashModes();
1957        if (isSupported(flashMode, supportedFlash)) {
1958            mParameters.setFlashMode(flashMode);
1959        } else {
1960            flashMode = mParameters.getFlashMode();
1961            if (flashMode == null) {
1962                flashMode = mActivity.getString(
1963                        R.string.pref_camera_flashmode_no_flash);
1964            }
1965        }
1966
1967        // Set white balance parameter.
1968        String whiteBalance = mPreferences.getString(
1969                CameraSettings.KEY_WHITE_BALANCE,
1970                mActivity.getString(R.string.pref_camera_whitebalance_default));
1971        if (isSupported(whiteBalance,
1972                mParameters.getSupportedWhiteBalance())) {
1973            mParameters.setWhiteBalance(whiteBalance);
1974        } else {
1975            whiteBalance = mParameters.getWhiteBalance();
1976            if (whiteBalance == null) {
1977                whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1978            }
1979        }
1980
1981        // Set zoom.
1982        if (mParameters.isZoomSupported()) {
1983            mParameters.setZoom(mZoomValue);
1984        }
1985
1986        // Set continuous autofocus.
1987        List<String> supportedFocus = mParameters.getSupportedFocusModes();
1988        if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) {
1989            mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
1990        }
1991
1992        mParameters.set(Util.RECORDING_HINT, Util.TRUE);
1993
1994        // Enable video stabilization. Convenience methods not available in API
1995        // level <= 14
1996        String vstabSupported = mParameters.get("video-stabilization-supported");
1997        if ("true".equals(vstabSupported)) {
1998            mParameters.set("video-stabilization", "true");
1999        }
2000
2001        // Set picture size.
2002        // The logic here is different from the logic in still-mode camera.
2003        // There we determine the preview size based on the picture size, but
2004        // here we determine the picture size based on the preview size.
2005        List<Size> supported = mParameters.getSupportedPictureSizes();
2006        Size optimalSize = Util.getOptimalVideoSnapshotPictureSize(supported,
2007                (double) mDesiredPreviewWidth / mDesiredPreviewHeight);
2008        Size original = mParameters.getPictureSize();
2009        if (!original.equals(optimalSize)) {
2010            mParameters.setPictureSize(optimalSize.width, optimalSize.height);
2011        }
2012        Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" +
2013                optimalSize.height);
2014
2015        // Set JPEG quality.
2016        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
2017                CameraProfile.QUALITY_HIGH);
2018        mParameters.setJpegQuality(jpegQuality);
2019
2020        mActivity.mCameraDevice.setParameters(mParameters);
2021        // Keep preview size up to date.
2022        mParameters = mActivity.mCameraDevice.getParameters();
2023
2024        updateCameraScreenNailSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
2025    }
2026
2027    private void updateCameraScreenNailSize(int width, int height) {
2028        if (!ApiHelper.HAS_SURFACE_TEXTURE) return;
2029
2030        if (mCameraDisplayOrientation % 180 != 0) {
2031            int tmp = width;
2032            width = height;
2033            height = tmp;
2034        }
2035
2036        CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
2037        int oldWidth = screenNail.getWidth();
2038        int oldHeight = screenNail.getHeight();
2039
2040        if (oldWidth != width || oldHeight != height) {
2041            screenNail.setSize(width, height);
2042            mActivity.notifyScreenNailChanged();
2043        }
2044
2045        if (screenNail.getSurfaceTexture() == null) {
2046            screenNail.acquireSurfaceTexture();
2047        }
2048    }
2049
2050    @Override
2051    public void onActivityResult(int requestCode, int resultCode, Intent data) {
2052        switch (requestCode) {
2053            case REQUEST_EFFECT_BACKDROPPER:
2054                if (resultCode == Activity.RESULT_OK) {
2055                    // onActivityResult() runs before onResume(), so this parameter will be
2056                    // seen by startPreview from onResume()
2057                    mEffectUriFromGallery = data.getData().toString();
2058                    Log.v(TAG, "Received URI from gallery: " + mEffectUriFromGallery);
2059                    mResetEffect = false;
2060                } else {
2061                    mEffectUriFromGallery = null;
2062                    Log.w(TAG, "No URI from gallery");
2063                    mResetEffect = true;
2064                }
2065                break;
2066        }
2067    }
2068
2069    @Override
2070    public void onEffectsUpdate(int effectId, int effectMsg) {
2071        Log.v(TAG, "onEffectsUpdate. Effect Message = " + effectMsg);
2072        if (effectMsg == EffectsRecorder.EFFECT_MSG_EFFECTS_STOPPED) {
2073            // Effects have shut down. Hide learning message if any,
2074            // and restart regular preview.
2075            mBgLearningMessageFrame.setVisibility(View.GONE);
2076            checkQualityAndStartPreview();
2077        } else if (effectMsg == EffectsRecorder.EFFECT_MSG_RECORDING_DONE) {
2078            // This follows the codepath from onStopVideoRecording.
2079            if (mEffectsDisplayResult && !addVideoToMediaStore()) {
2080                if (mIsVideoCaptureIntent) {
2081                    if (mQuickCapture) {
2082                        doReturnToCaller(true);
2083                    } else {
2084                        showAlert();
2085                    }
2086                }
2087            }
2088            mEffectsDisplayResult = false;
2089            // In onPause, these were not called if the effects were active. We
2090            // had to wait till the effects recording is complete to do this.
2091            if (mPaused) {
2092                closeVideoFileDescriptor();
2093                clearVideoNamer();
2094            }
2095        } else if (effectMsg == EffectsRecorder.EFFECT_MSG_PREVIEW_RUNNING) {
2096            // Enable the shutter button once the preview is complete.
2097            mShutterButton.setEnabled(true);
2098        } else if (effectId == EffectsRecorder.EFFECT_BACKDROPPER) {
2099            switch (effectMsg) {
2100                case EffectsRecorder.EFFECT_MSG_STARTED_LEARNING:
2101                    mBgLearningMessageFrame.setVisibility(View.VISIBLE);
2102                    break;
2103                case EffectsRecorder.EFFECT_MSG_DONE_LEARNING:
2104                case EffectsRecorder.EFFECT_MSG_SWITCHING_EFFECT:
2105                    mBgLearningMessageFrame.setVisibility(View.GONE);
2106                    break;
2107            }
2108        }
2109        // In onPause, this was not called if the effects were active. We had to
2110        // wait till the effects completed to do this.
2111        if (mPaused) {
2112            Log.v(TAG, "OnEffectsUpdate: closing effects if activity paused");
2113            closeEffects();
2114        }
2115    }
2116
2117    public void onCancelBgTraining(View v) {
2118        // Remove training message
2119        mBgLearningMessageFrame.setVisibility(View.GONE);
2120        // Write default effect out to shared prefs
2121        writeDefaultEffectToPrefs();
2122        // Tell the indicator controller to redraw based on new shared pref values
2123//        mIndicatorControlContainer.reloadPreferences();
2124        // Tell VideoCamer to re-init based on new shared pref values.
2125        onSharedPreferenceChanged();
2126    }
2127
2128    @Override
2129    public synchronized void onEffectsError(Exception exception, String fileName) {
2130        // TODO: Eventually we may want to show the user an error dialog, and then restart the
2131        // camera and encoder gracefully. For now, we just delete the file and bail out.
2132        if (fileName != null && new File(fileName).exists()) {
2133            deleteVideoFile(fileName);
2134        }
2135        try {
2136            if (Class.forName("android.filterpacks.videosink.MediaRecorderStopException")
2137                    .isInstance(exception)) {
2138                Log.w(TAG, "Problem recoding video file. Removing incomplete file.");
2139                return;
2140            }
2141        } catch (ClassNotFoundException ex) {
2142            Log.w(TAG, ex);
2143        }
2144        throw new RuntimeException("Error during recording!", exception);
2145    }
2146
2147    private void initializeControlByIntent() {
2148        if (mIsVideoCaptureIntent) {
2149            mActivity.hideSwitcher();
2150            // Cannot use RotateImageView for "done" and "cancel" button because
2151            // the tablet layout uses RotateLayout, which cannot be cast to
2152            // RotateImageView.
2153            mReviewDoneButton = (Rotatable) mRootView.findViewById(R.id.btn_done);
2154            mReviewCancelButton = (Rotatable) mRootView.findViewById(R.id.btn_cancel);
2155            mReviewPlayButton = (RotateImageView) mRootView.findViewById(R.id.btn_play);
2156
2157            ((View) mReviewCancelButton).setVisibility(View.VISIBLE);
2158
2159            ((View) mReviewDoneButton).setOnClickListener(new OnClickListener() {
2160                @Override
2161                public void onClick(View v) {
2162                    onReviewDoneClicked(v);
2163                }
2164            });
2165            ((View) mReviewCancelButton).setOnClickListener(new OnClickListener() {
2166                @Override
2167                public void onClick(View v) {
2168                    onReviewCancelClicked(v);
2169                }
2170            });
2171
2172            ((View) mReviewPlayButton).setOnClickListener(new OnClickListener() {
2173                @Override
2174                public void onClick(View v) {
2175                    onReviewPlayClicked(v);
2176                }
2177            });
2178
2179
2180            // Not grayed out upon disabled, to make the follow-up fade-out
2181            // effect look smooth. Note that the review done button in tablet
2182            // layout is not a TwoStateImageView.
2183            if (mReviewDoneButton instanceof TwoStateImageView) {
2184                ((TwoStateImageView) mReviewDoneButton).enableFilter(false);
2185            }
2186        }
2187    }
2188
2189    private void initializeMiscControls() {
2190        mPreviewFrameLayout = (PreviewFrameLayout) mRootView.findViewById(R.id.frame);
2191        mPreviewFrameLayout.setOnLayoutChangeListener(mActivity);
2192        mReviewImage = (ImageView) mRootView.findViewById(R.id.review_image);
2193
2194        mShutterButton = mActivity.getShutterButton();
2195        mShutterButton.setImageResource(R.drawable.btn_new_shutter_video);
2196        mShutterButton.setOnShutterButtonListener(this);
2197        mShutterButton.requestFocus();
2198
2199        // Disable the shutter button if effects are ON since it might take
2200        // a little more time for the effects preview to be ready. We do not
2201        // want to allow recording before that happens. The shutter button
2202        // will be enabled when we get the message from effectsrecorder that
2203        // the preview is running. This becomes critical when the camera is
2204        // swapped.
2205        if (effectsActive()) {
2206            mShutterButton.setEnabled(false);
2207        }
2208
2209        mRecordingTimeView = (TextView) mRootView.findViewById(R.id.recording_time);
2210        mRecordingTimeRect = (RotateLayout) mRootView.findViewById(R.id.recording_time_rect);
2211        mTimeLapseLabel = mRootView.findViewById(R.id.time_lapse_label);
2212        // The R.id.labels can only be found in phone layout.
2213        // That is, mLabelsLinearLayout should be null in tablet layout.
2214        mLabelsLinearLayout = (LinearLayout) mRootView.findViewById(R.id.labels);
2215
2216        mBgLearningMessageRotater = (RotateLayout) mRootView.findViewById(R.id.bg_replace_message);
2217        mBgLearningMessageFrame = mRootView.findViewById(R.id.bg_replace_message_frame);
2218    }
2219
2220    @Override
2221    public void onConfigurationChanged(Configuration newConfig) {
2222        setDisplayOrientation();
2223
2224        // Change layout in response to configuration change
2225        LayoutInflater inflater = mActivity.getLayoutInflater();
2226        ((ViewGroup) mRootView).removeAllViews();
2227        inflater.inflate(R.layout.video_module, (ViewGroup) mRootView);
2228
2229        // from onCreate()
2230        initializeControlByIntent();
2231        initializeOverlay();
2232        initializeSurfaceView();
2233        initializeMiscControls();
2234        showTimeLapseUI(mCaptureTimeLapse);
2235        initializeVideoSnapshot();
2236        resizeForPreviewAspectRatio();
2237        initializeVideoControl();
2238
2239        // from onResume()
2240        showVideoSnapshotUI(false);
2241        initializeZoom();
2242    }
2243
2244    @Override
2245    public void onOverriddenPreferencesClicked() {
2246    }
2247
2248    @Override
2249    // TODO: Delete this after old camera code is removed
2250    public void onRestorePreferencesClicked() {
2251    }
2252
2253    private boolean effectsActive() {
2254        return (mEffectType != EffectsRecorder.EFFECT_NONE);
2255    }
2256
2257    @Override
2258    public void onSharedPreferenceChanged() {
2259        // ignore the events after "onPause()" or preview has not started yet
2260        if (mPaused) return;
2261        synchronized (mPreferences) {
2262            // If mCameraDevice is not ready then we can set the parameter in
2263            // startPreview().
2264            if (mActivity.mCameraDevice == null) return;
2265
2266            boolean recordLocation = RecordLocationPreference.get(
2267                    mPreferences, mContentResolver);
2268            mLocationManager.recordLocation(recordLocation);
2269
2270            // Check if the current effects selection has changed
2271            if (updateEffectSelection()) return;
2272
2273            readVideoPreferences();
2274            showTimeLapseUI(mCaptureTimeLapse);
2275            // We need to restart the preview if preview size is changed.
2276            Size size = mParameters.getPreviewSize();
2277            if (size.width != mDesiredPreviewWidth
2278                    || size.height != mDesiredPreviewHeight) {
2279                if (!effectsActive()) {
2280                    stopPreview();
2281                } else {
2282                    mEffectsRecorder.release();
2283                    mEffectsRecorder = null;
2284                }
2285                resizeForPreviewAspectRatio();
2286                startPreview(); // Parameters will be set in startPreview().
2287            } else {
2288                setCameraParameters();
2289            }
2290        }
2291    }
2292
2293    private void switchCamera() {
2294        if (mPaused) return;
2295
2296        Log.d(TAG, "Start to switch camera.");
2297        mCameraId = mPendingSwitchCameraId;
2298        mPendingSwitchCameraId = -1;
2299        mVideoControl.setCameraId(mCameraId);
2300
2301        closeCamera();
2302
2303        // Restart the camera and initialize the UI. From onCreate.
2304        mPreferences.setLocalId(mActivity, mCameraId);
2305        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2306        openCamera();
2307        readVideoPreferences();
2308        startPreview();
2309        initializeVideoSnapshot();
2310        resizeForPreviewAspectRatio();
2311        initializeVideoControl();
2312
2313        // From onResume
2314        initializeZoom();
2315        setOrientationIndicator(mOrientationCompensation, false);
2316
2317        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2318            // Start switch camera animation. Post a message because
2319            // onFrameAvailable from the old camera may already exist.
2320            mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
2321        }
2322    }
2323
2324    // Preview texture has been copied. Now camera can be released and the
2325    // animation can be started.
2326    @Override
2327    public void onPreviewTextureCopied() {
2328        mHandler.sendEmptyMessage(SWITCH_CAMERA);
2329    }
2330
2331    @Override
2332    public void onCaptureTextureCopied() {
2333    }
2334
2335    private boolean updateEffectSelection() {
2336        int previousEffectType = mEffectType;
2337        Object previousEffectParameter = mEffectParameter;
2338        mEffectType = CameraSettings.readEffectType(mPreferences);
2339        mEffectParameter = CameraSettings.readEffectParameter(mPreferences);
2340
2341        if (mEffectType == previousEffectType) {
2342            if (mEffectType == EffectsRecorder.EFFECT_NONE) return false;
2343            if (mEffectParameter.equals(previousEffectParameter)) return false;
2344        }
2345        Log.v(TAG, "New effect selection: " + mPreferences.getString(
2346                CameraSettings.KEY_VIDEO_EFFECT, "none"));
2347
2348        if (mEffectType == EffectsRecorder.EFFECT_NONE) {
2349            // Stop effects and return to normal preview
2350            mEffectsRecorder.stopPreview();
2351            mPreviewing = false;
2352            return true;
2353        }
2354        if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER &&
2355            ((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) {
2356            // Request video from gallery to use for background
2357            Intent i = new Intent(Intent.ACTION_PICK);
2358            i.setDataAndType(Video.Media.EXTERNAL_CONTENT_URI,
2359                             "video/*");
2360            i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
2361            mActivity.startActivityForResult(i, REQUEST_EFFECT_BACKDROPPER);
2362            return true;
2363        }
2364        if (previousEffectType == EffectsRecorder.EFFECT_NONE) {
2365            // Stop regular preview and start effects.
2366            stopPreview();
2367            checkQualityAndStartPreview();
2368        } else {
2369            // Switch currently running effect
2370            mEffectsRecorder.setEffect(mEffectType, mEffectParameter);
2371        }
2372        return true;
2373    }
2374
2375    // Verifies that the current preview view size is correct before starting
2376    // preview. If not, resets the surface texture and resizes the view.
2377    private void checkQualityAndStartPreview() {
2378        readVideoPreferences();
2379        showTimeLapseUI(mCaptureTimeLapse);
2380        Size size = mParameters.getPreviewSize();
2381        if (size.width != mDesiredPreviewWidth
2382                || size.height != mDesiredPreviewHeight) {
2383            resizeForPreviewAspectRatio();
2384        }
2385        // Start up preview again
2386        startPreview();
2387    }
2388
2389    private void showTimeLapseUI(boolean enable) {
2390        if (mTimeLapseLabel != null) {
2391            mTimeLapseLabel.setVisibility(enable ? View.VISIBLE : View.GONE);
2392        }
2393    }
2394
2395    @Override
2396    public boolean dispatchTouchEvent(MotionEvent m) {
2397        if (mSwitchingCamera) return true;
2398        if (mPopup == null && mGestures != null && mRenderOverlay != null) {
2399            return mGestures.dispatchTouch(m);
2400        } else if (mPopup != null) {
2401            return mActivity.superDispatchTouchEvent(m);
2402        }
2403        return false;
2404    }
2405
2406    private class ZoomChangeListener implements ZoomRenderer.OnZoomChangedListener {
2407        @Override
2408        public void onZoomValueChanged(int index) {
2409            // Not useful to change zoom value when the activity is paused.
2410            if (mPaused) return;
2411
2412            mZoomValue = index;
2413
2414            // Set zoom parameters asynchronously
2415            mParameters.setZoom(mZoomValue);
2416            mActivity.mCameraDevice.setParametersAsync(mParameters);
2417        }
2418
2419        @Override
2420        public void onZoomStart() {
2421        }
2422        @Override
2423        public void onZoomEnd() {
2424        }
2425    }
2426
2427    private void initializeZoom() {
2428        if (!mParameters.isZoomSupported()) return;
2429        mZoomMax = mParameters.getMaxZoom();
2430        // Currently we use immediate zoom for fast zooming to get better UX and
2431        // there is no plan to take advantage of the smooth zoom.
2432        mZoomRenderer.setZoomMax(mZoomMax);
2433        mZoomRenderer.setZoomIndex(mParameters.getZoom());
2434        mZoomRenderer.setOnZoomChangeListener(new ZoomChangeListener());
2435        if (!mParameters.isZoomSupported()) return;
2436
2437        mZoomMax = mParameters.getMaxZoom();
2438        // Currently we use immediate zoom for fast zooming to get better UX and
2439        // there is no plan to take advantage of the smooth zoom.
2440    }
2441
2442    private void initializeVideoSnapshot() {
2443        if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
2444            mActivity.setSingleTapUpListener(mPreviewFrameLayout);
2445            // Show the tap to focus toast if this is the first start.
2446            if (mPreferences.getBoolean(
2447                        CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, true)) {
2448                // Delay the toast for one second to wait for orientation.
2449                mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_SNAPSHOT_TOAST, 1000);
2450            }
2451        } else {
2452            mActivity.setSingleTapUpListener(null);
2453        }
2454    }
2455
2456    void showVideoSnapshotUI(boolean enabled) {
2457        if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
2458            if (ApiHelper.HAS_SURFACE_TEXTURE && enabled) {
2459                ((CameraScreenNail) mActivity.mCameraScreenNail).animateCapture(getCameraRotation());
2460            } else {
2461                mPreviewFrameLayout.showBorder(enabled);
2462            }
2463//            mIndicatorControlContainer.enableZoom(!enabled);
2464            mShutterButton.setEnabled(!enabled);
2465        }
2466    }
2467
2468    // Preview area is touched. Take a picture.
2469    @Override
2470    public void onSingleTapUp(View view, int x, int y) {
2471        if (mMediaRecorderRecording && effectsActive()) {
2472            new RotateTextToast(mActivity, R.string.disable_video_snapshot_hint,
2473                    mOrientation).show();
2474            return;
2475        }
2476
2477        if (mPaused || mSnapshotInProgress || effectsActive()) {
2478            return;
2479        }
2480
2481        if (!mMediaRecorderRecording) {
2482            // check for dismissing popup
2483            if (mPopup != null) {
2484                dismissPopup(true);
2485            } else if (mPieRenderer != null) {
2486                mPieRenderer.setFocus(x, y, true);
2487            }
2488            return;
2489        }
2490
2491        // Set rotation and gps data.
2492        int rotation = Util.getJpegRotation(mCameraId, mOrientation);
2493        mParameters.setRotation(rotation);
2494        Location loc = mLocationManager.getCurrentLocation();
2495        Util.setGpsParameters(mParameters, loc);
2496        mActivity.mCameraDevice.setParameters(mParameters);
2497
2498        Log.v(TAG, "Video snapshot start");
2499        mActivity.mCameraDevice.takePicture(null, null, null, new JpegPictureCallback(loc));
2500        showVideoSnapshotUI(true);
2501        mSnapshotInProgress = true;
2502    }
2503
2504    @Override
2505    public void updateCameraAppView() {
2506        if (!mPreviewing || mParameters.getFlashMode() == null) return;
2507
2508        // When going to and back from gallery, we need to turn off/on the flash.
2509        if (!mActivity.mShowCameraAppView) {
2510            if (mParameters.getFlashMode().equals(Parameters.FLASH_MODE_OFF)) {
2511                mRestoreFlash = false;
2512                return;
2513            }
2514            mRestoreFlash = true;
2515            setCameraParameters();
2516        } else if (mRestoreFlash) {
2517            mRestoreFlash = false;
2518            setCameraParameters();
2519        }
2520    }
2521
2522    @Override
2523    public void onFullScreenChanged(boolean full) {
2524        if (mGestures != null) {
2525            mGestures.setEnabled(full);
2526        }
2527        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2528            if (mActivity.mCameraScreenNail != null) {
2529                ((CameraScreenNail) mActivity.mCameraScreenNail).setFullScreen(full);
2530            }
2531            return;
2532        }
2533        if (full) {
2534            mPreviewSurfaceView.expand();
2535        } else {
2536            mPreviewSurfaceView.shrink();
2537        }
2538    }
2539
2540    private final class JpegPictureCallback implements PictureCallback {
2541        Location mLocation;
2542
2543        public JpegPictureCallback(Location loc) {
2544            mLocation = loc;
2545        }
2546
2547        @Override
2548        public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) {
2549            Log.v(TAG, "onPictureTaken");
2550            mSnapshotInProgress = false;
2551            showVideoSnapshotUI(false);
2552            storeImage(jpegData, mLocation);
2553        }
2554    }
2555
2556    private void storeImage(final byte[] data, Location loc) {
2557        long dateTaken = System.currentTimeMillis();
2558        String title = Util.createJpegName(dateTaken);
2559        int orientation = Exif.getOrientation(data);
2560        Size s = mParameters.getPictureSize();
2561        Uri uri = Storage.addImage(mContentResolver, title, dateTaken, loc, orientation, data,
2562                s.width, s.height);
2563        if (uri != null) {
2564            Util.broadcastNewPicture(mActivity, uri);
2565        }
2566    }
2567
2568    private boolean resetEffect() {
2569        if (mResetEffect) {
2570            String value = mPreferences.getString(CameraSettings.KEY_VIDEO_EFFECT,
2571                    mPrefVideoEffectDefault);
2572            if (!mPrefVideoEffectDefault.equals(value)) {
2573                writeDefaultEffectToPrefs();
2574                return true;
2575            }
2576        }
2577        mResetEffect = true;
2578        return false;
2579    }
2580
2581    private String convertOutputFormatToMimeType(int outputFileFormat) {
2582        if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
2583            return "video/mp4";
2584        }
2585        return "video/3gpp";
2586    }
2587
2588    private String convertOutputFormatToFileExt(int outputFileFormat) {
2589        if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
2590            return ".mp4";
2591        }
2592        return ".3gp";
2593    }
2594
2595    private void closeVideoFileDescriptor() {
2596        if (mVideoFileDescriptor != null) {
2597            try {
2598                mVideoFileDescriptor.close();
2599            } catch (IOException e) {
2600                Log.e(TAG, "Fail to close fd", e);
2601            }
2602            mVideoFileDescriptor = null;
2603        }
2604    }
2605
2606    private void showTapToSnapshotToast() {
2607        new RotateTextToast(mActivity, R.string.video_snapshot_hint, mOrientationCompensation)
2608                .show();
2609        // Clear the preference.
2610        Editor editor = mPreferences.edit();
2611        editor.putBoolean(CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, false);
2612        editor.apply();
2613    }
2614
2615    private void clearVideoNamer() {
2616        if (mVideoNamer != null) {
2617            mVideoNamer.finish();
2618            mVideoNamer = null;
2619        }
2620    }
2621
2622    private static class VideoNamer extends Thread {
2623        private boolean mRequestPending;
2624        private ContentResolver mResolver;
2625        private ContentValues mValues;
2626        private boolean mStop;
2627        private Uri mUri;
2628
2629        // Runs in main thread
2630        public VideoNamer() {
2631            start();
2632        }
2633
2634        // Runs in main thread
2635        public synchronized void prepareUri(
2636                ContentResolver resolver, ContentValues values) {
2637            mRequestPending = true;
2638            mResolver = resolver;
2639            mValues = new ContentValues(values);
2640            notifyAll();
2641        }
2642
2643        // Runs in main thread
2644        public synchronized Uri getUri() {
2645            // wait until the request is done.
2646            while (mRequestPending) {
2647                try {
2648                    wait();
2649                } catch (InterruptedException ex) {
2650                    // ignore.
2651                }
2652            }
2653            Uri uri = mUri;
2654            mUri = null;
2655            return uri;
2656        }
2657
2658        // Runs in namer thread
2659        @Override
2660        public synchronized void run() {
2661            while (true) {
2662                if (mStop) break;
2663                if (!mRequestPending) {
2664                    try {
2665                        wait();
2666                    } catch (InterruptedException ex) {
2667                        // ignore.
2668                    }
2669                    continue;
2670                }
2671                cleanOldUri();
2672                generateUri();
2673                mRequestPending = false;
2674                notifyAll();
2675            }
2676            cleanOldUri();
2677        }
2678
2679        // Runs in main thread
2680        public synchronized void finish() {
2681            mStop = true;
2682            notifyAll();
2683        }
2684
2685        // Runs in namer thread
2686        private void generateUri() {
2687            Uri videoTable = Uri.parse("content://media/external/video/media");
2688            mUri = mResolver.insert(videoTable, mValues);
2689        }
2690
2691        // Runs in namer thread
2692        private void cleanOldUri() {
2693            if (mUri == null) return;
2694            mResolver.delete(mUri, null, null);
2695            mUri = null;
2696        }
2697    }
2698
2699    private class SurfaceViewCallback implements SurfaceHolder.Callback {
2700        public SurfaceViewCallback() {}
2701
2702        @Override
2703        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
2704            Log.v(TAG, "Surface changed. width=" + width + ". height=" + height);
2705        }
2706
2707        @Override
2708        public void surfaceCreated(SurfaceHolder holder) {
2709            Log.v(TAG, "Surface created");
2710            mSurfaceViewReady = true;
2711            if (mPaused) return;
2712            if (!ApiHelper.HAS_SURFACE_TEXTURE) {
2713                mActivity.mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder());
2714                if (!mPreviewing) {
2715                    startPreview();
2716                }
2717            }
2718        }
2719
2720        @Override
2721        public void surfaceDestroyed(SurfaceHolder holder) {
2722            Log.v(TAG, "Surface destroyed");
2723            mSurfaceViewReady = false;
2724            if (mPaused) return;
2725            if (!ApiHelper.HAS_SURFACE_TEXTURE) {
2726                stopVideoRecording();
2727                stopPreview();
2728            }
2729        }
2730    }
2731
2732    @Override
2733    public boolean updateStorageHintOnResume() {
2734        return true;
2735    }
2736
2737    // required by OnPreferenceChangedListener
2738    @Override
2739    public void onCameraPickerClicked(int cameraId) {
2740        if (mPaused || mPendingSwitchCameraId != -1) return;
2741
2742        mPendingSwitchCameraId = cameraId;
2743        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2744            Log.d(TAG, "Start to copy texture.");
2745            // We need to keep a preview frame for the animation before
2746            // releasing the camera. This will trigger onPreviewTextureCopied.
2747            ((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
2748            // Disable all camera controls.
2749            mSwitchingCamera = true;
2750        } else {
2751            switchCamera();
2752        }
2753    }
2754
2755    @Override
2756    public boolean needsSwitcher() {
2757        return !mIsVideoCaptureIntent;
2758    }
2759
2760    @Override
2761    public void onPieOpened(int centerX, int centerY) {
2762        mActivity.cancelActivityTouchHandling();
2763        mActivity.setSwipingEnabled(false);
2764    }
2765
2766    @Override
2767    public void onPieClosed() {
2768        mActivity.setSwipingEnabled(true);
2769    }
2770
2771    public void showPopup(AbstractSettingPopup popup) {
2772        mActivity.hideUI();
2773        mPopup = popup;
2774        // Make sure popup is brought up with the right orientation
2775        mPopup.setOrientation(mOrientationCompensation, false);
2776        mPopup.setVisibility(View.VISIBLE);
2777        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
2778                LayoutParams.WRAP_CONTENT);
2779        lp.gravity = Gravity.CENTER;
2780        ((FrameLayout) mRootView).addView(mPopup, lp);
2781    }
2782
2783    public void dismissPopup(boolean topLevelPopupOnly) {
2784        mActivity.showUI();
2785        if (mPopup != null) {
2786            ((FrameLayout) mRootView).removeView(mPopup);
2787            mPopup = null;
2788        }
2789        mVideoControl.popupDismissed(topLevelPopupOnly);
2790    }
2791
2792
2793}
2794