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