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