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