2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.camera;
19 import android.annotation.TargetApi;
20 import android.app.Activity;
21 import android.content.ActivityNotFoundException;
22 import android.content.BroadcastReceiver;
23 import android.content.ContentResolver;
24 import android.content.ContentValues;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.IntentFilter;
28 import android.graphics.Bitmap;
29 import android.graphics.Point;
30 import android.graphics.SurfaceTexture;
31 import android.location.Location;
32 import android.media.AudioManager;
33 import android.media.CamcorderProfile;
34 import android.media.CameraProfile;
35 import android.media.MediaRecorder;
36 import android.net.Uri;
37 import android.os.Build;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.Message;
41 import android.os.ParcelFileDescriptor;
42 import android.os.SystemClock;
43 import android.provider.MediaStore;
44 import android.provider.MediaStore.MediaColumns;
45 import android.provider.MediaStore.Video;
46 import android.view.KeyEvent;
47 import android.view.OrientationEventListener;
48 import android.view.View;
49 import android.widget.Toast;
51 import com.android.camera.app.AppController;
52 import com.android.camera.app.CameraAppUI;
53 import com.android.camera.app.LocationManager;
54 import com.android.camera.app.MediaSaver;
55 import com.android.camera.app.MemoryManager;
56 import com.android.camera.app.MemoryManager.MemoryListener;
57 import com.android.camera.debug.Log;
58 import com.android.camera.exif.ExifInterface;
59 import com.android.camera.hardware.HardwareSpec;
60 import com.android.camera.hardware.HardwareSpecImpl;
61 import com.android.camera.module.ModuleController;
62 import com.android.camera.settings.Keys;
63 import com.android.camera.settings.SettingsManager;
64 import com.android.camera.settings.SettingsUtil;
65 import com.android.camera.ui.TouchCoordinate;
66 import com.android.camera.util.ApiHelper;
67 import com.android.camera.util.CameraUtil;
68 import com.android.camera.util.UsageStatistics;
69 import com.android.camera2.R;
70 import com.android.ex.camera2.portability.CameraAgent;
71 import com.android.ex.camera2.portability.CameraAgent.CameraPictureCallback;
72 import com.android.ex.camera2.portability.CameraAgent.CameraProxy;
73 import com.android.ex.camera2.portability.CameraCapabilities;
74 import com.android.ex.camera2.portability.CameraDeviceInfo.Characteristics;
75 import com.android.ex.camera2.portability.CameraSettings;
76 import com.android.ex.camera2.portability.Size;
77 import com.google.common.logging.eventprotos;
80 import java.io.IOException;
81 import java.text.SimpleDateFormat;
82 import java.util.ArrayList;
83 import java.util.Date;
84 import java.util.Iterator;
85 import java.util.List;
88 public class VideoModule extends CameraModule
89 implements ModuleController,
92 MediaRecorder.OnErrorListener,
93 MediaRecorder.OnInfoListener, FocusOverlayManager.Listener {
95 private static final String VIDEO_MODULE_STRING_ID = "VideoModule";
97 private static final Log.Tag TAG = new Log.Tag(VIDEO_MODULE_STRING_ID);
99 // Messages defined for the UI thread handler.
100 private static final int MSG_CHECK_DISPLAY_ROTATION = 4;
101 private static final int MSG_UPDATE_RECORD_TIME = 5;
102 private static final int MSG_ENABLE_SHUTTER_BUTTON = 6;
103 private static final int MSG_SWITCH_CAMERA = 8;
104 private static final int MSG_SWITCH_CAMERA_START_ANIMATION = 9;
106 private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms
109 * An unpublished intent flag requesting to start recording straight away
110 * and return as soon as recording is stopped.
111 * TODO: consider publishing by moving into MediaStore.
113 private static final String EXTRA_QUICK_CAPTURE =
114 "android.intent.extra.quickCapture";
117 private CameraActivity mActivity;
118 private boolean mPaused;
120 // if, during and intent capture, the activity is paused (e.g. when app switching or reviewing a
121 // shot video), we don't want the bottom bar intent ui to reset to the capture button
122 private boolean mDontResetIntentUiOnResume;
124 private int mCameraId;
125 private CameraSettings mCameraSettings;
126 private CameraCapabilities mCameraCapabilities;
128 private boolean mIsInReviewMode;
129 private boolean mSnapshotInProgress = false;
131 private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
133 // Preference must be read before starting preview. We check this before starting
135 private boolean mPreferenceRead;
137 private boolean mIsVideoCaptureIntent;
138 private boolean mQuickCapture;
140 private MediaRecorder mMediaRecorder;
142 private boolean mSwitchingCamera;
143 private boolean mMediaRecorderRecording = false;
144 private long mRecordingStartTime;
145 private boolean mRecordingTimeCountsDown = false;
146 private long mOnResumeTime;
147 // The video file that the hardware camera is about to record into
148 // (or is recording into.
149 private String mVideoFilename;
150 private ParcelFileDescriptor mVideoFileDescriptor;
152 // The video file that has already been recorded, and that is being
153 // examined by the user.
154 private String mCurrentVideoFilename;
155 private Uri mCurrentVideoUri;
156 private boolean mCurrentVideoUriFromMediaSaved;
157 private ContentValues mCurrentVideoValues;
159 private CamcorderProfile mProfile;
161 // The video duration limit. 0 means no limit.
162 private int mMaxVideoDurationInMs;
164 boolean mPreviewing = false; // True if preview is started.
165 // The display rotation in degrees. This is only valid when mPreviewing is
167 private int mDisplayRotation;
168 private int mCameraDisplayOrientation;
169 private AppController mAppController;
171 private int mDesiredPreviewWidth;
172 private int mDesiredPreviewHeight;
173 private ContentResolver mContentResolver;
175 private LocationManager mLocationManager;
177 private int mPendingSwitchCameraId;
178 private final Handler mHandler = new MainHandler();
180 private CameraProxy mCameraDevice;
182 // The degrees of the device rotated clockwise from its natural orientation.
183 private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
185 private int mZoomValue; // The current zoom value.
187 private final MediaSaver.OnMediaSavedListener mOnVideoSavedListener =
188 new MediaSaver.OnMediaSavedListener() {
190 public void onMediaSaved(Uri uri) {
192 mCurrentVideoUri = uri;
193 mCurrentVideoUriFromMediaSaved = true;
195 mActivity.notifyNewMedia(uri);
200 private final MediaSaver.OnMediaSavedListener mOnPhotoSavedListener =
201 new MediaSaver.OnMediaSavedListener() {
203 public void onMediaSaved(Uri uri) {
205 mActivity.notifyNewMedia(uri);
209 private FocusOverlayManager mFocusManager;
210 private boolean mMirror;
211 private boolean mFocusAreaSupported;
212 private boolean mMeteringAreaSupported;
214 private final CameraAgent.CameraAFCallback mAutoFocusCallback =
215 new CameraAgent.CameraAFCallback() {
217 public void onAutoFocus(boolean focused, CameraProxy camera) {
221 mFocusManager.onAutoFocus(focused, false);
225 private final Object mAutoFocusMoveCallback =
226 ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
227 ? new CameraAgent.CameraAFMoveCallback() {
229 public void onAutoFocusMoving(boolean moving, CameraProxy camera) {
230 mFocusManager.onAutoFocusMoving(moving);
235 * This Handler is used to post message back onto the main thread of the
238 private class MainHandler extends Handler {
240 public void handleMessage(Message msg) {
243 case MSG_ENABLE_SHUTTER_BUTTON:
244 mAppController.setShutterEnabled(true);
247 case MSG_UPDATE_RECORD_TIME: {
248 updateRecordingTime();
252 case MSG_CHECK_DISPLAY_ROTATION: {
253 // Restart the preview if display rotation has changed.
254 // Sometimes this happens when the device is held upside
255 // down and camera app is opened. Rotation animation will
256 // take some time and the rotation value we have got may be
257 // wrong. Framework does not have a callback for this now.
258 if ((CameraUtil.getDisplayRotation(mActivity) != mDisplayRotation)
259 && !mMediaRecorderRecording && !mSwitchingCamera) {
262 if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
263 mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100);
268 case MSG_SWITCH_CAMERA: {
273 case MSG_SWITCH_CAMERA_START_ANIMATION: {
275 //((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
277 // Enable all camera controls.
278 mSwitchingCamera = false;
283 Log.v(TAG, "Unhandled message: " + msg.what);
289 private BroadcastReceiver mReceiver = null;
291 private class MyBroadcastReceiver extends BroadcastReceiver {
293 public void onReceive(Context context, Intent intent) {
294 String action = intent.getAction();
295 if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
296 stopVideoRecording();
297 } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
298 Toast.makeText(mActivity,
299 mActivity.getResources().getString(R.string.wait), Toast.LENGTH_LONG).show();
304 private int mShutterIconId;
308 * Construct a new video module.
310 public VideoModule(AppController app) {
315 public String getPeekAccessibilityString() {
316 return mAppController.getAndroidContext()
317 .getResources().getString(R.string.video_accessibility_peek);
320 private String createName(long dateTaken) {
321 Date date = new Date(dateTaken);
322 SimpleDateFormat dateFormat = new SimpleDateFormat(
323 mActivity.getString(R.string.video_file_name_format));
325 return dateFormat.format(date);
329 public String getModuleStringIdentifier() {
330 return VIDEO_MODULE_STRING_ID;
334 public void init(CameraActivity activity, boolean isSecureCamera, boolean isCaptureIntent) {
335 mActivity = activity;
336 // TODO: Need to look at the controller interface to see if we can get
337 // rid of passing in the activity directly.
338 mAppController = mActivity;
340 mActivity.updateStorageSpaceAndHint(null);
342 mUI = new VideoUI(mActivity, this, mActivity.getModuleLayoutRoot());
343 mActivity.setPreviewStatusListener(mUI);
345 SettingsManager settingsManager = mActivity.getSettingsManager();
346 mCameraId = settingsManager.getInteger(mAppController.getModuleScope(),
350 * To reduce startup time, we start the preview in another thread.
351 * We make sure the preview is started at the end of onCreate.
353 requestCamera(mCameraId);
355 mContentResolver = mActivity.getContentResolver();
357 // Surface texture is from camera screen nail and startPreview needs it.
358 // This must be done before startPreview.
359 mIsVideoCaptureIntent = isVideoCaptureIntent();
361 mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
362 mLocationManager = mActivity.getLocationManager();
364 mUI.setOrientationIndicator(0, false);
365 setDisplayOrientation();
367 mPendingSwitchCameraId = -1;
369 mShutterIconId = CameraUtil.getCameraShutterIconId(
370 mAppController.getCurrentModuleIndex(), mAppController.getAndroidContext());
374 public boolean isUsingBottomBar() {
378 private void initializeControlByIntent() {
379 if (isVideoCaptureIntent()) {
380 if (!mDontResetIntentUiOnResume) {
381 mActivity.getCameraAppUI().transitionToIntentCaptureLayout();
384 mDontResetIntentUiOnResume = false;
389 public void onSingleTapUp(View view, int x, int y) {
390 if (mPaused || mCameraDevice == null) {
393 if (mMediaRecorderRecording) {
394 if (!mSnapshotInProgress) {
399 // Check if metering area or focus area is supported.
400 if (!mFocusAreaSupported && !mMeteringAreaSupported) {
404 mFocusManager.onSingleTapUp(x, y);
407 private void takeASnapshot() {
408 // Only take snapshots if video snapshot is supported by device
409 if(!mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT)) {
410 Log.w(TAG, "Cannot take a video snapshot - not supported by hardware");
413 if (!mIsVideoCaptureIntent) {
414 if (!mMediaRecorderRecording || mPaused || mSnapshotInProgress
415 || !mAppController.isShutterEnabled()) {
419 Location loc = mLocationManager.getCurrentLocation();
420 CameraUtil.setGpsParameters(mCameraSettings, loc);
421 mCameraDevice.applySettings(mCameraSettings);
423 Log.i(TAG, "Video snapshot start");
424 mCameraDevice.takePicture(mHandler,
425 null, null, null, new JpegPictureCallback(loc));
426 showVideoSnapshotUI(true);
427 mSnapshotInProgress = true;
431 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
432 private void updateAutoFocusMoveCallback() {
437 if (mCameraSettings.getCurrentFocusMode() == CameraCapabilities.FocusMode.CONTINUOUS_PICTURE) {
438 mCameraDevice.setAutoFocusMoveCallback(mHandler,
439 (CameraAgent.CameraAFMoveCallback) mAutoFocusMoveCallback);
441 mCameraDevice.setAutoFocusMoveCallback(null, null);
446 * @return Whether the currently active camera is front-facing.
448 private boolean isCameraFrontFacing() {
449 return mAppController.getCameraProvider().getCharacteristics(mCameraId)
454 * @return Whether the currently active camera is back-facing.
456 private boolean isCameraBackFacing() {
457 return mAppController.getCameraProvider().getCharacteristics(mCameraId)
462 * The focus manager gets initialized after camera is available.
464 private void initializeFocusManager() {
465 // Create FocusManager object. startPreview needs it.
466 // if mFocusManager not null, reuse it
467 // otherwise create a new instance
468 if (mFocusManager != null) {
469 mFocusManager.removeMessages();
471 mMirror = isCameraFrontFacing();
472 String[] defaultFocusModesStrings = mActivity.getResources().getStringArray(
473 R.array.pref_camera_focusmode_default_array);
474 CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier();
475 ArrayList<CameraCapabilities.FocusMode> defaultFocusModes =
476 new ArrayList<CameraCapabilities.FocusMode>();
477 for (String modeString : defaultFocusModesStrings) {
478 CameraCapabilities.FocusMode mode = stringifier.focusModeFromString(modeString);
480 defaultFocusModes.add(mode);
483 mFocusManager = new FocusOverlayManager(mAppController,
484 defaultFocusModes, mCameraCapabilities, this, mMirror,
485 mActivity.getMainLooper(), mUI.getFocusUI());
487 mAppController.addPreviewAreaSizeChangedListener(mFocusManager);
491 public void onOrientationChanged(int orientation) {
492 // We keep the last known orientation. So if the user first orient
493 // the camera then point the camera to floor or sky, we still have
494 // the correct orientation.
495 if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
498 int newOrientation = CameraUtil.roundOrientation(orientation, mOrientation);
500 if (mOrientation != newOrientation) {
501 mOrientation = newOrientation;
503 mUI.onOrientationChanged(orientation);
507 private final ButtonManager.ButtonCallback mFlashCallback =
508 new ButtonManager.ButtonCallback() {
510 public void onStateChanged(int state) {
511 // Update flash parameters.
512 enableTorchMode(true);
516 private final ButtonManager.ButtonCallback mCameraCallback =
517 new ButtonManager.ButtonCallback() {
519 public void onStateChanged(int state) {
520 if (mPaused || mAppController.getCameraProvider().waitingForCamera()) {
523 mPendingSwitchCameraId = state;
524 Log.d(TAG, "Start to copy texture.");
526 // Disable all camera controls.
527 mSwitchingCamera = true;
532 private final View.OnClickListener mCancelCallback = new View.OnClickListener() {
534 public void onClick(View v) {
535 onReviewCancelClicked(v);
539 private final View.OnClickListener mDoneCallback = new View.OnClickListener() {
541 public void onClick(View v) {
542 onReviewDoneClicked(v);
545 private final View.OnClickListener mReviewCallback = new View.OnClickListener() {
547 public void onClick(View v) {
548 onReviewPlayClicked(v);
553 public void hardResetSettings(SettingsManager settingsManager) {
554 // VideoModule does not need to hard reset any settings.
558 public HardwareSpec getHardwareSpec() {
559 return (mCameraSettings != null ?
560 new HardwareSpecImpl(getCameraProvider(), mCameraCapabilities) : null);
564 public CameraAppUI.BottomBarUISpec getBottomBarSpec() {
565 CameraAppUI.BottomBarUISpec bottomBarSpec = new CameraAppUI.BottomBarUISpec();
567 bottomBarSpec.enableCamera = true;
568 bottomBarSpec.cameraCallback = mCameraCallback;
569 bottomBarSpec.enableTorchFlash = true;
570 bottomBarSpec.flashCallback = mFlashCallback;
571 bottomBarSpec.hideHdr = true;
572 bottomBarSpec.enableGridLines = true;
574 if (isVideoCaptureIntent()) {
575 bottomBarSpec.showCancel = true;
576 bottomBarSpec.cancelCallback = mCancelCallback;
577 bottomBarSpec.showDone = true;
578 bottomBarSpec.doneCallback = mDoneCallback;
579 bottomBarSpec.showReview = true;
580 bottomBarSpec.reviewCallback = mReviewCallback;
583 return bottomBarSpec;
587 public void onCameraAvailable(CameraProxy cameraProxy) {
588 mCameraDevice = cameraProxy;
589 mCameraCapabilities = mCameraDevice.getCapabilities();
590 mCameraSettings = mCameraDevice.getSettings();
591 mFocusAreaSupported = mCameraCapabilities.supports(CameraCapabilities.Feature.FOCUS_AREA);
592 mMeteringAreaSupported =
593 mCameraCapabilities.supports(CameraCapabilities.Feature.METERING_AREA);
594 readVideoPreferences();
595 resizeForPreviewAspectRatio();
596 initializeFocusManager();
597 // TODO: Having focus overlay manager caching the parameters is prone to error,
598 // we should consider passing the parameters to focus overlay to ensure the
599 // parameters are up to date.
600 mFocusManager.updateCapabilities(mCameraCapabilities);
603 initializeVideoSnapshot();
604 mUI.initializeZoom(mCameraSettings, mCameraCapabilities);
605 initializeControlByIntent();
608 private void startPlayVideoActivity() {
609 Intent intent = new Intent(Intent.ACTION_VIEW);
610 intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat));
613 .startActivityForResult(intent, CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW);
614 } catch (ActivityNotFoundException ex) {
615 Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex);
621 public void onReviewPlayClicked(View v) {
622 startPlayVideoActivity();
627 public void onReviewDoneClicked(View v) {
628 mIsInReviewMode = false;
629 doReturnToCaller(true);
634 public void onReviewCancelClicked(View v) {
635 // TODO: It should be better to not even insert the URI at all before we
636 // confirm done in review, which means we need to handle temporary video
637 // files in a quite different way than we currently had.
638 // Make sure we don't delete the Uri sent from the video capture intent.
639 if (mCurrentVideoUriFromMediaSaved) {
640 mContentResolver.delete(mCurrentVideoUri, null, null);
642 mIsInReviewMode = false;
643 doReturnToCaller(false);
647 public boolean isInReviewMode() {
648 return mIsInReviewMode;
651 private void onStopVideoRecording() {
652 mAppController.getCameraAppUI().setSwipeEnabled(true);
653 boolean recordFail = stopVideoRecording();
654 if (mIsVideoCaptureIntent) {
656 doReturnToCaller(!recordFail);
657 } else if (!recordFail) {
660 } else if (!recordFail){
661 // Start capture animation.
662 if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
663 // The capture animation is disabled on ICS because we use SurfaceView
664 // for preview during recording. When the recording is done, we switch
665 // back to use SurfaceTexture for preview and we need to stop then start
666 // the preview. This will cause the preview flicker since the preview
667 // will not be continuous for a short period of time.
674 public void onVideoSaved() {
675 if (mIsVideoCaptureIntent) {
680 public void onProtectiveCurtainClick(View v) {
685 public void onShutterButtonClick() {
686 if (mSwitchingCamera) {
689 boolean stop = mMediaRecorderRecording;
692 onStopVideoRecording();
694 startVideoRecording();
696 mAppController.setShutterEnabled(false);
697 mFocusManager.onShutterUp(mCameraSettings.getCurrentFocusMode());
699 // Keep the shutter button disabled when in video capture intent
700 // mode and recording is stopped. It'll be re-enabled when
701 // re-take button is clicked.
702 if (!(mIsVideoCaptureIntent && stop)) {
703 mHandler.sendEmptyMessageDelayed(MSG_ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT);
708 public void onShutterCoordinate(TouchCoordinate coord) {
713 public void onShutterButtonFocus(boolean pressed) {
714 // TODO: Remove this when old camera controls are removed from the UI.
717 private void readVideoPreferences() {
718 // The preference stores values from ListPreference and is thus string type for all values.
719 // We need to convert it to int manually.
720 SettingsManager settingsManager = mActivity.getSettingsManager();
721 if (!settingsManager.isSet(SettingsManager.SCOPE_GLOBAL,
722 Keys.KEY_VIDEO_QUALITY_BACK)) {
723 settingsManager.setToDefault(SettingsManager.SCOPE_GLOBAL,
724 Keys.KEY_VIDEO_QUALITY_BACK);
726 // TODO: Remove this once 4k recording is stable enough on new devices.
727 // Don't set the default resolution to be large if the device supports 4k video.
728 if (CamcorderProfile.hasProfile(mCameraId, CamcorderProfile.QUALITY_2160P)) {
729 settingsManager.set(SettingsManager.SCOPE_GLOBAL,
730 Keys.KEY_VIDEO_QUALITY_BACK,
731 mAppController.getAndroidContext().getString(R.string.pref_video_quality_medium));
734 if (!settingsManager.isSet(SettingsManager.SCOPE_GLOBAL,
735 Keys.KEY_VIDEO_QUALITY_FRONT)) {
736 settingsManager.setToDefault(SettingsManager.SCOPE_GLOBAL,
737 Keys.KEY_VIDEO_QUALITY_FRONT);
739 String videoQualityKey = isCameraFrontFacing() ? Keys.KEY_VIDEO_QUALITY_FRONT
740 : Keys.KEY_VIDEO_QUALITY_BACK;
741 String videoQuality = settingsManager
742 .getString(SettingsManager.SCOPE_GLOBAL, videoQualityKey);
743 int quality = SettingsUtil.getVideoQuality(videoQuality, mCameraId);
744 Log.d(TAG, "Selected video quality for '" + videoQuality + "' is " + quality);
746 // Set video quality.
747 Intent intent = mActivity.getIntent();
748 if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
749 int extraVideoQuality =
750 intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
751 if (extraVideoQuality > 0) {
752 quality = CamcorderProfile.QUALITY_HIGH;
753 } else { // 0 is mms.
754 quality = CamcorderProfile.QUALITY_LOW;
758 // Set video duration limit. The limit is read from the preference,
759 // unless it is specified in the intent.
760 if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
762 intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0);
763 mMaxVideoDurationInMs = 1000 * seconds;
765 mMaxVideoDurationInMs = SettingsUtil.getMaxVideoDuration(mActivity
766 .getAndroidContext());
769 // If quality is not supported, request QUALITY_HIGH which is always supported.
770 if (CamcorderProfile.hasProfile(mCameraId, quality) == false) {
771 quality = CamcorderProfile.QUALITY_HIGH;
773 mProfile = CamcorderProfile.get(mCameraId, quality);
774 mPreferenceRead = true;
775 if (mCameraDevice == null) {
778 mCameraSettings = mCameraDevice.getSettings();
779 Point desiredPreviewSize = getDesiredPreviewSize(mAppController.getAndroidContext(),
780 mCameraSettings, mCameraCapabilities, mProfile, mUI.getPreviewScreenSize());
781 mDesiredPreviewWidth = desiredPreviewSize.x;
782 mDesiredPreviewHeight = desiredPreviewSize.y;
783 mUI.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
784 Log.v(TAG, "mDesiredPreviewWidth=" + mDesiredPreviewWidth +
785 ". mDesiredPreviewHeight=" + mDesiredPreviewHeight);
788 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
790 * Calculates the preview size and stores it in mDesiredPreviewWidth and
791 * mDesiredPreviewHeight.
793 * <p>This function checks {@link
794 * com.android.camera.cameradevice.CameraCapabilities#getPreferredPreviewSizeForVideo()}
795 * but also considers the current preview area size on screen and make sure
796 * the final preview size will not be smaller than 1/2 of the current
797 * on screen preview area in terms of their short sides.</p>
799 * @return The preferred preview size or {@code null} if the camera is not
802 private static Point getDesiredPreviewSize(Context context, CameraSettings settings,
803 CameraCapabilities capabilities, CamcorderProfile profile, Point previewScreenSize) {
804 if (capabilities.getSupportedVideoSizes() == null) {
805 // Driver doesn't support separate outputs for preview and video.
806 return new Point(profile.videoFrameWidth, profile.videoFrameHeight);
809 final int previewScreenShortSide = (previewScreenSize.x < previewScreenSize.y ?
810 previewScreenSize.x : previewScreenSize.y);
811 List<Size> sizes = capabilities.getSupportedPreviewSizes();
812 Size preferred = capabilities.getPreferredPreviewSizeForVideo();
813 final int preferredPreviewSizeShortSide = (preferred.width() < preferred.height() ?
814 preferred.width() : preferred.height());
815 if (preferredPreviewSizeShortSide * 2 < previewScreenShortSide) {
816 preferred = new Size(profile.videoFrameWidth, profile.videoFrameHeight);
818 int product = preferred.width() * preferred.height();
819 Iterator<Size> it = sizes.iterator();
820 // Remove the preview sizes that are not preferred.
821 while (it.hasNext()) {
822 Size size = it.next();
823 if (size.width() * size.height() > product) {
827 Size optimalSize = CameraUtil.getOptimalPreviewSize(context, sizes,
828 (double) profile.videoFrameWidth / profile.videoFrameHeight);
829 return new Point(optimalSize.width(), optimalSize.height());
832 private void resizeForPreviewAspectRatio() {
833 mUI.setAspectRatio((float) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
836 private void installIntentFilter() {
837 // install an intent filter to receive SD card related events.
838 IntentFilter intentFilter =
839 new IntentFilter(Intent.ACTION_MEDIA_EJECT);
840 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
841 intentFilter.addDataScheme("file");
842 mReceiver = new MyBroadcastReceiver();
843 mActivity.registerReceiver(mReceiver, intentFilter);
846 private void setDisplayOrientation() {
847 mDisplayRotation = CameraUtil.getDisplayRotation(mActivity);
848 Characteristics info =
849 mActivity.getCameraProvider().getCharacteristics(mCameraId);
850 mCameraDisplayOrientation = info.getPreviewOrientation(mDisplayRotation);
851 // Change the camera display orientation
852 if (mCameraDevice != null) {
853 mCameraDevice.setDisplayOrientation(mDisplayRotation);
855 if (mFocusManager != null) {
856 mFocusManager.setDisplayOrientation(mCameraDisplayOrientation);
861 public void updateCameraOrientation() {
862 if (mMediaRecorderRecording) {
865 if (mDisplayRotation != CameraUtil.getDisplayRotation(mActivity)) {
866 setDisplayOrientation();
871 public void updatePreviewAspectRatio(float aspectRatio) {
872 mAppController.updatePreviewAspectRatio(aspectRatio);
876 * Returns current Zoom value, with 1.0 as the value for no zoom.
878 private float currentZoomValue() {
879 float zoomValue = 1.0f;
880 if (mCameraCapabilities.supports(CameraCapabilities.Feature.ZOOM)) {
881 int zoomIndex = mCameraSettings.getCurrentZoomIndex();
882 List<Integer> zoomRatios = mCameraCapabilities.getZoomRatioList();
883 if (zoomRatios != null && zoomIndex < zoomRatios.size()) {
884 zoomValue = 0.01f * zoomRatios.get(zoomIndex);
891 public int onZoomChanged(int index) {
892 // Not useful to change zoom value when the activity is paused.
897 if (mCameraSettings == null || mCameraDevice == null) {
900 // Set zoom parameters asynchronously
901 mCameraSettings.setZoomIndex(mZoomValue);
902 mCameraDevice.applySettings(mCameraSettings);
903 CameraSettings settings = mCameraDevice.getSettings();
904 if (settings != null) {
905 return settings.getCurrentZoomIndex();
910 private void startPreview() {
911 Log.i(TAG, "startPreview");
913 SurfaceTexture surfaceTexture = mActivity.getCameraAppUI().getSurfaceTexture();
914 if (!mPreferenceRead || surfaceTexture == null || mPaused == true ||
915 mCameraDevice == null) {
919 mCameraDevice.setErrorCallback(mHandler, mErrorCallback);
920 if (mPreviewing == true) {
924 setDisplayOrientation();
925 mCameraDevice.setDisplayOrientation(mDisplayRotation);
926 setCameraParameters();
928 if (mFocusManager != null) {
929 // If the focus mode is continuous autofocus, call cancelAutoFocus
930 // to resume it because it may have been paused by autoFocus call.
931 CameraCapabilities.FocusMode focusMode =
932 mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode());
933 if (focusMode == CameraCapabilities.FocusMode.CONTINUOUS_PICTURE) {
934 mCameraDevice.cancelAutoFocus();
938 // This is to notify app controller that preview will start next, so app
939 // controller can set preview callbacks if needed. This has to happen before
940 // preview is started as a workaround of the framework issue related to preview
941 // callbacks that causes preview stretch and crash. (More details see b/12210027
943 mAppController.onPreviewReadyToStart();
945 mCameraDevice.setPreviewTexture(surfaceTexture);
946 mCameraDevice.startPreview();
949 } catch (Throwable ex) {
951 throw new RuntimeException("startPreview failed", ex);
955 private void onPreviewStarted() {
956 mAppController.setShutterEnabled(true);
957 mAppController.onPreviewStarted();
958 if (mFocusManager != null) {
959 mFocusManager.onPreviewStarted();
964 public void onPreviewInitialDataReceived() {
968 public void stopPreview() {
972 mCameraDevice.stopPreview();
973 if (mFocusManager != null) {
974 mFocusManager.onPreviewStopped();
979 private void closeCamera() {
980 Log.i(TAG, "closeCamera");
981 if (mCameraDevice == null) {
982 Log.d(TAG, "already stopped.");
985 mCameraDevice.setZoomChangeListener(null);
986 mCameraDevice.setErrorCallback(null, null);
987 mActivity.getCameraProvider().releaseCamera(mCameraDevice.getCameraId());
988 mCameraDevice = null;
990 mSnapshotInProgress = false;
991 if (mFocusManager != null) {
992 mFocusManager.onCameraReleased();
997 public boolean onBackPressed() {
1001 if (mMediaRecorderRecording) {
1002 onStopVideoRecording();
1010 public boolean onKeyDown(int keyCode, KeyEvent event) {
1011 // Do not handle any key if the activity is paused.
1017 case KeyEvent.KEYCODE_CAMERA:
1018 if (event.getRepeatCount() == 0) {
1019 onShutterButtonClick();
1022 case KeyEvent.KEYCODE_DPAD_CENTER:
1023 if (event.getRepeatCount() == 0) {
1024 onShutterButtonClick();
1027 case KeyEvent.KEYCODE_MENU:
1028 // Consume menu button presses during capture.
1029 return mMediaRecorderRecording;
1035 public boolean onKeyUp(int keyCode, KeyEvent event) {
1037 case KeyEvent.KEYCODE_CAMERA:
1038 onShutterButtonClick();
1040 case KeyEvent.KEYCODE_MENU:
1041 // Consume menu button presses during capture.
1042 return mMediaRecorderRecording;
1048 public boolean isVideoCaptureIntent() {
1049 String action = mActivity.getIntent().getAction();
1050 return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action));
1053 private void doReturnToCaller(boolean valid) {
1054 Intent resultIntent = new Intent();
1057 resultCode = Activity.RESULT_OK;
1058 resultIntent.setData(mCurrentVideoUri);
1060 resultCode = Activity.RESULT_CANCELED;
1062 mActivity.setResultEx(resultCode, resultIntent);
1066 private void cleanupEmptyFile() {
1067 if (mVideoFilename != null) {
1068 File f = new File(mVideoFilename);
1069 if (f.length() == 0 && f.delete()) {
1070 Log.v(TAG, "Empty video file deleted: " + mVideoFilename);
1071 mVideoFilename = null;
1076 // Prepares media recorder.
1077 private void initializeRecorder() {
1078 Log.i(TAG, "initializeRecorder");
1079 // If the mCameraDevice is null, then this activity is going to finish
1080 if (mCameraDevice == null) {
1084 Intent intent = mActivity.getIntent();
1085 Bundle myExtras = intent.getExtras();
1087 long requestedSizeLimit = 0;
1088 closeVideoFileDescriptor();
1089 mCurrentVideoUriFromMediaSaved = false;
1090 if (mIsVideoCaptureIntent && myExtras != null) {
1091 Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1092 if (saveUri != null) {
1094 mVideoFileDescriptor =
1095 mContentResolver.openFileDescriptor(saveUri, "rw");
1096 mCurrentVideoUri = saveUri;
1097 } catch (java.io.FileNotFoundException ex) {
1099 Log.e(TAG, ex.toString());
1102 requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
1104 mMediaRecorder = new MediaRecorder();
1106 // Unlock the camera object before passing it to media recorder.
1107 mCameraDevice.unlock();
1108 mMediaRecorder.setCamera(mCameraDevice.getCamera());
1109 mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
1110 mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
1111 mMediaRecorder.setProfile(mProfile);
1112 mMediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
1113 mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs);
1115 setRecordLocation();
1118 // Try Uri in the intent first. If it doesn't exist, use our own
1120 if (mVideoFileDescriptor != null) {
1121 mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
1123 generateVideoFilename(mProfile.fileFormat);
1124 mMediaRecorder.setOutputFile(mVideoFilename);
1127 // Set maximum file size.
1128 long maxFileSize = mActivity.getStorageSpaceBytes() - Storage.LOW_STORAGE_THRESHOLD_BYTES;
1129 if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
1130 maxFileSize = requestedSizeLimit;
1134 mMediaRecorder.setMaxFileSize(maxFileSize);
1135 } catch (RuntimeException exception) {
1136 // We are going to ignore failure of setMaxFileSize here, as
1137 // a) The composer selected may simply not support it, or
1138 // b) The underlying media framework may not handle 64-bit range
1139 // on the size restriction.
1142 // See com.android.camera.cameradevice.CameraSettings.setPhotoRotationDegrees
1143 // for documentation.
1144 // Note that mOrientation here is the device orientation, which is the opposite of
1145 // what activity.getWindowManager().getDefaultDisplay().getRotation() would return,
1146 // which is the orientation the graphics need to rotate in order to render correctly.
1148 if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
1149 Characteristics info =
1150 mActivity.getCameraProvider().getCharacteristics(mCameraId);
1151 if (isCameraFrontFacing()) {
1152 rotation = (info.getSensorOrientation() - mOrientation + 360) % 360;
1153 } else if (isCameraBackFacing()) {
1154 rotation = (info.getSensorOrientation() + mOrientation) % 360;
1156 Log.e(TAG, "Camera is facing unhandled direction");
1159 mMediaRecorder.setOrientationHint(rotation);
1162 mMediaRecorder.prepare();
1163 } catch (IOException e) {
1164 Log.e(TAG, "prepare failed for " + mVideoFilename, e);
1165 releaseMediaRecorder();
1166 throw new RuntimeException(e);
1169 mMediaRecorder.setOnErrorListener(this);
1170 mMediaRecorder.setOnInfoListener(this);
1173 private static void setCaptureRate(MediaRecorder recorder, double fps) {
1174 recorder.setCaptureRate(fps);
1177 private void setRecordLocation() {
1178 Location loc = mLocationManager.getCurrentLocation();
1180 mMediaRecorder.setLocation((float) loc.getLatitude(),
1181 (float) loc.getLongitude());
1185 private void releaseMediaRecorder() {
1186 Log.i(TAG, "Releasing media recorder.");
1187 if (mMediaRecorder != null) {
1189 mMediaRecorder.reset();
1190 mMediaRecorder.release();
1191 mMediaRecorder = null;
1193 mVideoFilename = null;
1196 private void generateVideoFilename(int outputFileFormat) {
1197 long dateTaken = System.currentTimeMillis();
1198 String title = createName(dateTaken);
1199 // Used when emailing.
1200 String filename = title + convertOutputFormatToFileExt(outputFileFormat);
1201 String mime = convertOutputFormatToMimeType(outputFileFormat);
1202 String path = Storage.DIRECTORY + '/' + filename;
1203 String tmpPath = path + ".tmp";
1204 mCurrentVideoValues = new ContentValues(9);
1205 mCurrentVideoValues.put(Video.Media.TITLE, title);
1206 mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename);
1207 mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken);
1208 mCurrentVideoValues.put(MediaColumns.DATE_MODIFIED, dateTaken / 1000);
1209 mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime);
1210 mCurrentVideoValues.put(Video.Media.DATA, path);
1211 mCurrentVideoValues.put(Video.Media.WIDTH, mProfile.videoFrameWidth);
1212 mCurrentVideoValues.put(Video.Media.HEIGHT, mProfile.videoFrameHeight);
1213 mCurrentVideoValues.put(Video.Media.RESOLUTION,
1214 Integer.toString(mProfile.videoFrameWidth) + "x" +
1215 Integer.toString(mProfile.videoFrameHeight));
1216 Location loc = mLocationManager.getCurrentLocation();
1218 mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude());
1219 mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude());
1221 mVideoFilename = tmpPath;
1222 Log.v(TAG, "New video filename: " + mVideoFilename);
1225 private void logVideoCapture(long duration) {
1226 String flashSetting = mActivity.getSettingsManager()
1227 .getString(mAppController.getCameraScope(),
1228 Keys.KEY_VIDEOCAMERA_FLASH_MODE);
1229 boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager());
1230 int width = (Integer) mCurrentVideoValues.get(Video.Media.WIDTH);
1231 int height = (Integer) mCurrentVideoValues.get(Video.Media.HEIGHT);
1232 long size = new File(mCurrentVideoFilename).length();
1233 String name = new File(mCurrentVideoValues.getAsString(Video.Media.DATA)).getName();
1234 UsageStatistics.instance().videoCaptureDoneEvent(name, duration, isCameraFrontFacing(),
1235 currentZoomValue(), width, height, size, flashSetting, gridLinesOn);
1238 private void saveVideo() {
1239 if (mVideoFileDescriptor == null) {
1240 long duration = SystemClock.uptimeMillis() - mRecordingStartTime;
1244 Log.w(TAG, "Video duration <= 0 : " + duration);
1246 mCurrentVideoValues.put(Video.Media.SIZE, new File(mCurrentVideoFilename).length());
1247 mCurrentVideoValues.put(Video.Media.DURATION, duration);
1248 getServices().getMediaSaver().addVideo(mCurrentVideoFilename,
1249 mCurrentVideoValues, mOnVideoSavedListener, mContentResolver);
1250 logVideoCapture(duration);
1252 mCurrentVideoValues = null;
1255 private void deleteVideoFile(String fileName) {
1256 Log.v(TAG, "Deleting video " + fileName);
1257 File f = new File(fileName);
1259 Log.v(TAG, "Could not delete " + fileName);
1263 // from MediaRecorder.OnErrorListener
1265 public void onError(MediaRecorder mr, int what, int extra) {
1266 Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra);
1267 if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
1268 // We may have run out of space on the sdcard.
1269 stopVideoRecording();
1270 mActivity.updateStorageSpaceAndHint(null);
1274 // from MediaRecorder.OnInfoListener
1276 public void onInfo(MediaRecorder mr, int what, int extra) {
1277 if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
1278 if (mMediaRecorderRecording) {
1279 onStopVideoRecording();
1281 } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
1282 if (mMediaRecorderRecording) {
1283 onStopVideoRecording();
1287 Toast.makeText(mActivity, R.string.video_reach_size_limit,
1288 Toast.LENGTH_LONG).show();
1293 * Make sure we're not recording music playing in the background, ask the
1294 * MediaPlaybackService to pause playback.
1296 private void pauseAudioPlayback() {
1297 AudioManager am = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE);
1298 am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
1302 public boolean isRecording() {
1303 return mMediaRecorderRecording;
1306 private void startVideoRecording() {
1307 Log.i(TAG, "startVideoRecording");
1308 mUI.cancelAnimations();
1309 mUI.setSwipingEnabled(false);
1310 mUI.showFocusUI(false);
1311 mUI.showVideoRecordingHints(false);
1313 mActivity.updateStorageSpaceAndHint(new CameraActivity.OnStorageUpdateDoneListener() {
1315 public void onStorageUpdateDone(long bytes) {
1316 if (bytes <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
1317 Log.w(TAG, "Storage issue, ignore the start request");
1320 //if (!mCameraDevice.waitDone()) return;
1321 mCurrentVideoUri = null;
1323 initializeRecorder();
1324 if (mMediaRecorder == null) {
1325 Log.e(TAG, "Fail to initialize media recorder");
1329 pauseAudioPlayback();
1332 mMediaRecorder.start(); // Recording is now started
1333 } catch (RuntimeException e) {
1334 Log.e(TAG, "Could not start media recorder. ", e);
1335 releaseMediaRecorder();
1336 // If start fails, frameworks will not lock the camera for us.
1337 mCameraDevice.lock();
1340 mAppController.getCameraAppUI().setSwipeEnabled(false);
1342 // The parameters might have been altered by MediaRecorder already.
1343 // We need to force mCameraDevice to refresh before getting it.
1344 mCameraDevice.refreshSettings();
1345 // The parameters may have been changed by MediaRecorder upon starting
1346 // recording. We need to alter the parameters if we support camcorder
1347 // zoom. To reduce latency when setting the parameters during zoom, we
1348 // update the settings here once.
1349 mCameraSettings = mCameraDevice.getSettings();
1351 mMediaRecorderRecording = true;
1352 mActivity.lockOrientation();
1353 mRecordingStartTime = SystemClock.uptimeMillis();
1355 // A special case of mode options closing: during capture it should
1356 // not be possible to change mode state.
1357 mAppController.getCameraAppUI().hideModeOptions();
1358 mAppController.getCameraAppUI().animateBottomBarToVideoStop(R.drawable.ic_stop);
1359 mUI.showRecordingUI(true);
1361 setFocusParameters();
1363 updateRecordingTime();
1364 mActivity.enableKeepScreenOn(true);
1370 private Bitmap getVideoThumbnail() {
1371 Bitmap bitmap = null;
1372 if (mVideoFileDescriptor != null) {
1373 bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
1374 mDesiredPreviewWidth);
1375 } else if (mCurrentVideoUri != null) {
1377 mVideoFileDescriptor = mContentResolver.openFileDescriptor(mCurrentVideoUri, "r");
1378 bitmap = Thumbnail.createVideoThumbnailBitmap(
1379 mVideoFileDescriptor.getFileDescriptor(), mDesiredPreviewWidth);
1380 } catch (java.io.FileNotFoundException ex) {
1382 Log.e(TAG, ex.toString());
1386 if (bitmap != null) {
1387 // MetadataRetriever already rotates the thumbnail. We should rotate
1388 // it to match the UI orientation (and mirror if it is front-facing camera).
1389 bitmap = CameraUtil.rotateAndMirror(bitmap, 0, isCameraFrontFacing());
1394 private void showCaptureResult() {
1395 mIsInReviewMode = true;
1396 Bitmap bitmap = getVideoThumbnail();
1397 if (bitmap != null) {
1398 mUI.showReviewImage(bitmap);
1400 mUI.showReviewControls();
1403 private boolean stopVideoRecording() {
1404 Log.i(TAG, "stopVideoRecording");
1405 mUI.setSwipingEnabled(true);
1406 mUI.showFocusUI(true);
1407 mUI.showVideoRecordingHints(true);
1409 boolean fail = false;
1410 if (mMediaRecorderRecording) {
1411 boolean shouldAddToMediaStoreNow = false;
1414 mMediaRecorder.setOnErrorListener(null);
1415 mMediaRecorder.setOnInfoListener(null);
1416 mMediaRecorder.stop();
1417 shouldAddToMediaStoreNow = true;
1418 mCurrentVideoFilename = mVideoFilename;
1419 Log.v(TAG, "stopVideoRecording: current video filename: " + mCurrentVideoFilename);
1420 } catch (RuntimeException e) {
1421 Log.e(TAG, "stop fail", e);
1422 if (mVideoFilename != null) {
1423 deleteVideoFile(mVideoFilename);
1427 mMediaRecorderRecording = false;
1428 mActivity.unlockOrientation();
1430 // If the activity is paused, this means activity is interrupted
1431 // during recording. Release the camera as soon as possible because
1432 // face unlock or other applications may need to use the camera.
1437 mUI.showRecordingUI(false);
1438 // The orientation was fixed during video recording. Now make it
1439 // reflect the device orientation as video recording is stopped.
1440 mUI.setOrientationIndicator(0, true);
1441 mActivity.enableKeepScreenOn(false);
1442 if (shouldAddToMediaStoreNow && !fail) {
1443 if (mVideoFileDescriptor == null) {
1445 } else if (mIsVideoCaptureIntent) {
1446 // if no file save is needed, we can show the post capture UI now
1447 showCaptureResult();
1451 // release media recorder
1452 releaseMediaRecorder();
1454 mAppController.getCameraAppUI().showModeOptions();
1455 mAppController.getCameraAppUI().animateBottomBarToFullSize(mShutterIconId);
1457 setFocusParameters();
1458 mCameraDevice.lock();
1459 if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
1461 // Switch back to use SurfaceTexture for preview.
1464 // Update the parameters here because the parameters might have been altered
1465 // by MediaRecorder.
1466 mCameraSettings = mCameraDevice.getSettings();
1469 // Check this in advance of each shot so we don't add to shutter
1470 // latency. It's true that someone else could write to the SD card
1471 // in the mean time and fill it, but that could have happened
1472 // between the shutter press and saving the file too.
1473 mActivity.updateStorageSpaceAndHint(null);
1478 private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
1479 long seconds = milliSeconds / 1000; // round down to compute seconds
1480 long minutes = seconds / 60;
1481 long hours = minutes / 60;
1482 long remainderMinutes = minutes - (hours * 60);
1483 long remainderSeconds = seconds - (minutes * 60);
1485 StringBuilder timeStringBuilder = new StringBuilder();
1490 timeStringBuilder.append('0');
1492 timeStringBuilder.append(hours);
1494 timeStringBuilder.append(':');
1498 if (remainderMinutes < 10) {
1499 timeStringBuilder.append('0');
1501 timeStringBuilder.append(remainderMinutes);
1502 timeStringBuilder.append(':');
1505 if (remainderSeconds < 10) {
1506 timeStringBuilder.append('0');
1508 timeStringBuilder.append(remainderSeconds);
1511 if (displayCentiSeconds) {
1512 timeStringBuilder.append('.');
1513 long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
1514 if (remainderCentiSeconds < 10) {
1515 timeStringBuilder.append('0');
1517 timeStringBuilder.append(remainderCentiSeconds);
1520 return timeStringBuilder.toString();
1523 private void updateRecordingTime() {
1524 if (!mMediaRecorderRecording) {
1527 long now = SystemClock.uptimeMillis();
1528 long delta = now - mRecordingStartTime;
1530 // Starting a minute before reaching the max duration
1531 // limit, we'll countdown the remaining time instead.
1532 boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
1533 && delta >= mMaxVideoDurationInMs - 60000);
1535 long deltaAdjusted = delta;
1536 if (countdownRemainingTime) {
1537 deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
1541 long targetNextUpdateDelay;
1543 text = millisecondToTimeString(deltaAdjusted, false);
1544 targetNextUpdateDelay = 1000;
1546 mUI.setRecordingTime(text);
1548 if (mRecordingTimeCountsDown != countdownRemainingTime) {
1549 // Avoid setting the color on every update, do it only
1550 // when it needs changing.
1551 mRecordingTimeCountsDown = countdownRemainingTime;
1553 int color = mActivity.getResources().getColor(R.color.recording_time_remaining_text);
1555 mUI.setRecordingTimeTextColor(color);
1558 long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
1559 mHandler.sendEmptyMessageDelayed(MSG_UPDATE_RECORD_TIME, actualNextUpdateDelay);
1562 private static boolean isSupported(String value, List<String> supported) {
1563 return supported == null ? false : supported.indexOf(value) >= 0;
1566 @SuppressWarnings("deprecation")
1567 private void setCameraParameters() {
1568 SettingsManager settingsManager = mActivity.getSettingsManager();
1570 mCameraSettings.setPreviewSize(new Size(mDesiredPreviewWidth, mDesiredPreviewHeight));
1571 // This is required for Samsung SGH-I337 and probably other Samsung S4 versions
1572 if (Build.BRAND.toLowerCase().contains("samsung")) {
1573 mCameraSettings.setSetting("video-size",
1574 mProfile.videoFrameWidth + "x" + mProfile.videoFrameHeight);
1577 CameraUtil.getMaxPreviewFpsRange(mCameraCapabilities.getSupportedPreviewFpsRange());
1578 if (fpsRange.length > 0) {
1579 mCameraSettings.setPreviewFpsRange(fpsRange[0], fpsRange[1]);
1581 mCameraSettings.setPreviewFrameRate(mProfile.videoFrameRate);
1584 enableTorchMode(Keys.isCameraBackFacing(settingsManager, mAppController.getModuleScope()));
1587 if (mCameraCapabilities.supports(CameraCapabilities.Feature.ZOOM)) {
1588 mCameraSettings.setZoomIndex(mZoomValue);
1590 updateFocusParameters();
1592 mCameraSettings.setRecordingHintEnabled(true);
1594 if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_STABILIZATION)) {
1595 mCameraSettings.setVideoStabilization(true);
1598 // Set picture size.
1599 // The logic here is different from the logic in still-mode camera.
1600 // There we determine the preview size based on the picture size, but
1601 // here we determine the picture size based on the preview size.
1602 List<Size> supported = mCameraCapabilities.getSupportedPhotoSizes();
1603 Size optimalSize = CameraUtil.getOptimalVideoSnapshotPictureSize(supported,
1604 (double) mDesiredPreviewWidth / mDesiredPreviewHeight);
1605 Size original = new Size(mCameraSettings.getCurrentPhotoSize());
1606 if (!original.equals(optimalSize)) {
1607 mCameraSettings.setPhotoSize(optimalSize);
1609 Log.d(TAG, "Video snapshot size is " + optimalSize);
1611 // Set JPEG quality.
1612 int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1613 CameraProfile.QUALITY_HIGH);
1614 mCameraSettings.setPhotoJpegCompressionQuality(jpegQuality);
1616 mCameraDevice.applySettings(mCameraSettings);
1617 // Nexus 5 through KitKat 4.4.2 requires a second call to
1618 // .setParameters() for frame rate settings to take effect.
1619 mCameraDevice.applySettings(mCameraSettings);
1621 // Update UI based on the new parameters.
1622 mUI.updateOnScreenIndicators(mCameraSettings);
1625 private void updateFocusParameters() {
1626 // Set continuous autofocus. During recording, we use "continuous-video"
1627 // auto focus mode to ensure smooth focusing. Whereas during preview (i.e.
1628 // before recording starts) we use "continuous-picture" auto focus mode
1629 // for faster but slightly jittery focusing.
1630 Set<CameraCapabilities.FocusMode> supportedFocus = mCameraCapabilities
1631 .getSupportedFocusModes();
1632 if (mMediaRecorderRecording) {
1633 if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO)) {
1634 mCameraSettings.setFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
1635 mFocusManager.overrideFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
1637 mFocusManager.overrideFocusMode(null);
1640 // FIXME(b/16984793): This is broken. For some reasons, CONTINUOUS_PICTURE is not on
1641 // when preview starts.
1642 mFocusManager.overrideFocusMode(null);
1643 if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_PICTURE)) {
1644 mCameraSettings.setFocusMode(
1645 mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode()));
1646 if (mFocusAreaSupported) {
1647 mCameraSettings.setFocusAreas(mFocusManager.getFocusAreas());
1651 updateAutoFocusMoveCallback();
1655 public void resume() {
1656 if (isVideoCaptureIntent()) {
1657 mDontResetIntentUiOnResume = mPaused;
1661 installIntentFilter();
1662 mAppController.setShutterEnabled(false);
1665 showVideoSnapshotUI(false);
1668 requestCamera(mCameraId);
1670 // preview already started
1671 mAppController.setShutterEnabled(true);
1674 if (mFocusManager != null) {
1675 // If camera is not open when resume is called, focus manager will not
1676 // be initialized yet, in which case it will start listening to
1677 // preview area size change later in the initialization.
1678 mAppController.addPreviewAreaSizeChangedListener(mFocusManager);
1682 mOnResumeTime = SystemClock.uptimeMillis();
1683 mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100);
1685 getServices().getMemoryManager().addListener(this);
1689 public void pause() {
1692 if (mFocusManager != null) {
1693 // If camera is not open when resume is called, focus manager will not
1694 // be initialized yet, in which case it will start listening to
1695 // preview area size change later in the initialization.
1696 mAppController.removePreviewAreaSizeChangedListener(mFocusManager);
1697 mFocusManager.removeMessages();
1699 if (mMediaRecorderRecording) {
1700 // Camera will be released in onStopVideoRecording.
1701 onStopVideoRecording();
1705 releaseMediaRecorder();
1708 closeVideoFileDescriptor();
1710 if (mReceiver != null) {
1711 mActivity.unregisterReceiver(mReceiver);
1715 mHandler.removeMessages(MSG_CHECK_DISPLAY_ROTATION);
1716 mHandler.removeMessages(MSG_SWITCH_CAMERA);
1717 mHandler.removeMessages(MSG_SWITCH_CAMERA_START_ANIMATION);
1718 mPendingSwitchCameraId = -1;
1719 mSwitchingCamera = false;
1720 mPreferenceRead = false;
1721 getServices().getMemoryManager().removeListener(this);
1725 public void destroy() {
1730 public void onLayoutOrientationChanged(boolean isLandscape) {
1731 setDisplayOrientation();
1734 // TODO: integrate this into the SettingsManager listeners.
1735 public void onSharedPreferenceChanged() {
1739 private void switchCamera() {
1743 SettingsManager settingsManager = mActivity.getSettingsManager();
1745 Log.d(TAG, "Start to switch camera.");
1746 mCameraId = mPendingSwitchCameraId;
1747 mPendingSwitchCameraId = -1;
1748 settingsManager.set(mAppController.getModuleScope(),
1749 Keys.KEY_CAMERA_ID, mCameraId);
1751 if (mFocusManager != null) {
1752 mFocusManager.removeMessages();
1755 requestCamera(mCameraId);
1757 mMirror = isCameraFrontFacing();
1758 if (mFocusManager != null) {
1759 mFocusManager.setMirror(mMirror);
1764 mUI.setOrientationIndicator(0, false);
1766 // Start switch camera animation. Post a message because
1767 // onFrameAvailable from the old camera may already exist.
1768 mHandler.sendEmptyMessage(MSG_SWITCH_CAMERA_START_ANIMATION);
1769 mUI.updateOnScreenIndicators(mCameraSettings);
1772 private void initializeVideoSnapshot() {
1773 if (mCameraSettings == null) {
1778 void showVideoSnapshotUI(boolean enabled) {
1779 if (mCameraSettings == null) {
1782 if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT) &&
1783 !mIsVideoCaptureIntent) {
1787 mUI.showPreviewBorder(enabled);
1789 mAppController.setShutterEnabled(!enabled);
1794 * Used to update the flash mode. Video mode can turn on the flash as torch
1795 * mode, which we would like to turn on and off when we switching in and
1796 * out to the preview.
1798 * @param enable Whether torch mode can be enabled.
1800 private void enableTorchMode(boolean enable) {
1801 if (mCameraSettings.getCurrentFlashMode() == null) {
1805 SettingsManager settingsManager = mActivity.getSettingsManager();
1807 CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier();
1808 CameraCapabilities.FlashMode flashMode;
1810 flashMode = stringifier
1811 .flashModeFromString(settingsManager.getString(mAppController.getCameraScope(),
1812 Keys.KEY_VIDEOCAMERA_FLASH_MODE));
1814 flashMode = CameraCapabilities.FlashMode.OFF;
1816 if (mCameraCapabilities.supports(flashMode)) {
1817 mCameraSettings.setFlashMode(flashMode);
1819 /* TODO: Find out how to deal with the following code piece:
1821 flashMode = mCameraSettings.getCurrentFlashMode();
1822 if (flashMode == null) {
1823 flashMode = mActivity.getString(
1824 R.string.pref_camera_flashmode_no_flash);
1825 mParameters.setFlashMode(flashMode);
1828 mCameraDevice.applySettings(mCameraSettings);
1829 mUI.updateOnScreenIndicators(mCameraSettings);
1833 public void onPreviewVisibilityChanged(int visibility) {
1835 enableTorchMode(visibility == ModuleController.VISIBILITY_VISIBLE);
1839 private final class JpegPictureCallback implements CameraPictureCallback {
1842 public JpegPictureCallback(Location loc) {
1847 public void onPictureTaken(byte [] jpegData, CameraProxy camera) {
1848 Log.i(TAG, "Video snapshot taken.");
1849 mSnapshotInProgress = false;
1850 showVideoSnapshotUI(false);
1851 storeImage(jpegData, mLocation);
1855 private void storeImage(final byte[] data, Location loc) {
1856 long dateTaken = System.currentTimeMillis();
1857 String title = CameraUtil.createJpegName(dateTaken);
1858 ExifInterface exif = Exif.getExif(data);
1859 int orientation = Exif.getOrientation(exif);
1861 String flashSetting = mActivity.getSettingsManager()
1862 .getString(mAppController.getCameraScope(), Keys.KEY_VIDEOCAMERA_FLASH_MODE);
1863 Boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager());
1864 UsageStatistics.instance().photoCaptureDoneEvent(
1865 eventprotos.NavigationChange.Mode.VIDEO_STILL, title + ".jpeg", exif,
1866 isCameraFrontFacing(), false, currentZoomValue(), flashSetting, gridLinesOn,
1869 getServices().getMediaSaver().addImage(
1870 data, title, dateTaken, loc, orientation,
1871 exif, mOnPhotoSavedListener, mContentResolver);
1874 private String convertOutputFormatToMimeType(int outputFileFormat) {
1875 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
1878 return "video/3gpp";
1881 private String convertOutputFormatToFileExt(int outputFileFormat) {
1882 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
1888 private void closeVideoFileDescriptor() {
1889 if (mVideoFileDescriptor != null) {
1891 mVideoFileDescriptor.close();
1892 } catch (IOException e) {
1893 Log.e(TAG, "Fail to close fd", e);
1895 mVideoFileDescriptor = null;
1900 public void onPreviewUIReady() {
1905 public void onPreviewUIDestroyed() {
1910 public void startPreCaptureAnimation() {
1911 mAppController.startPreCaptureAnimation();
1914 private void requestCamera(int id) {
1915 mActivity.getCameraProvider().requestCamera(id);
1919 public void onMemoryStateChanged(int state) {
1920 mAppController.setShutterEnabled(state == MemoryManager.STATE_OK);
1924 public void onLowMemory() {
1925 // Not much we can do in the video module.
1928 /***********************FocusOverlayManager Listener****************************/
1930 public void autoFocus() {
1931 mCameraDevice.autoFocus(mHandler, mAutoFocusCallback);
1935 public void cancelAutoFocus() {
1936 mCameraDevice.cancelAutoFocus();
1937 setFocusParameters();
1941 public boolean capture() {
1946 public void startFaceDetection() {
1951 public void stopFaceDetection() {
1956 public void setFocusParameters() {
1957 updateFocusParameters();
1958 mCameraDevice.applySettings(mCameraSettings);