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