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