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