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