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