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