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.app.Activity;
20 import android.content.ActivityNotFoundException;
21 import android.content.BroadcastReceiver;
22 import android.content.ContentResolver;
23 import android.content.ContentValues;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.IntentFilter;
27 import android.graphics.Bitmap;
28 import android.graphics.Point;
29 import android.graphics.SurfaceTexture;
30 import android.hardware.Camera;
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.Looper;
41 import android.os.Message;
42 import android.os.ParcelFileDescriptor;
43 import android.os.SystemClock;
44 import android.provider.MediaStore;
45 import android.provider.MediaStore.MediaColumns;
46 import android.provider.MediaStore.Video;
47 import android.view.KeyEvent;
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.app.OrientationManager;
58 import com.android.camera.debug.Log;
59 import com.android.camera.exif.ExifInterface;
60 import com.android.camera.hardware.HardwareSpec;
61 import com.android.camera.hardware.HardwareSpecImpl;
62 import com.android.camera.module.ModuleController;
63 import com.android.camera.settings.Keys;
64 import com.android.camera.settings.SettingsManager;
65 import com.android.camera.settings.SettingsUtil;
66 import com.android.camera.ui.TouchCoordinate;
67 import com.android.camera.util.AndroidServices;
68 import com.android.camera.util.ApiHelper;
69 import com.android.camera.util.CameraUtil;
70 import com.android.camera.stats.UsageStatistics;
71 import com.android.camera.util.Size;
72 import com.android.camera2.R;
73 import com.android.ex.camera2.portability.CameraAgent;
74 import com.android.ex.camera2.portability.CameraAgent.CameraPictureCallback;
75 import com.android.ex.camera2.portability.CameraAgent.CameraProxy;
76 import com.android.ex.camera2.portability.CameraCapabilities;
77 import com.android.ex.camera2.portability.CameraDeviceInfo.Characteristics;
78 import com.android.ex.camera2.portability.CameraSettings;
79 import com.google.common.logging.eventprotos;
82 import java.io.IOException;
83 import java.text.SimpleDateFormat;
84 import java.util.ArrayList;
85 import java.util.Date;
86 import java.util.Iterator;
87 import java.util.List;
90 public class VideoModule extends CameraModule
91 implements FocusOverlayManager.Listener, MediaRecorder.OnErrorListener,
92 MediaRecorder.OnInfoListener, MemoryListener,
93 OrientationManager.OnOrientationChangeListener, VideoController {
95 private static final Log.Tag TAG = new Log.Tag("VideoModule");
97 // Messages defined for the UI thread handler.
98 private static final int MSG_CHECK_DISPLAY_ROTATION = 4;
99 private static final int MSG_UPDATE_RECORD_TIME = 5;
100 private static final int MSG_ENABLE_SHUTTER_BUTTON = 6;
101 private static final int MSG_SWITCH_CAMERA = 8;
102 private static final int MSG_SWITCH_CAMERA_START_ANIMATION = 9;
104 private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms
107 * An unpublished intent flag requesting to start recording straight away
108 * and return as soon as recording is stopped.
109 * TODO: consider publishing by moving into MediaStore.
111 private static final String EXTRA_QUICK_CAPTURE =
112 "android.intent.extra.quickCapture";
115 private CameraActivity mActivity;
116 private boolean mPaused;
118 // if, during and intent capture, the activity is paused (e.g. when app switching or reviewing a
119 // shot video), we don't want the bottom bar intent ui to reset to the capture button
120 private boolean mDontResetIntentUiOnResume;
122 private int mCameraId;
123 private CameraSettings mCameraSettings;
124 private CameraCapabilities mCameraCapabilities;
125 private HardwareSpec mHardwareSpec;
127 private boolean mIsInReviewMode;
128 private boolean mSnapshotInProgress = false;
130 // Preference must be read before starting preview. We check this before starting
132 private boolean mPreferenceRead;
134 private boolean mIsVideoCaptureIntent;
135 private boolean mQuickCapture;
137 private MediaRecorder mMediaRecorder;
138 /** Manager used to mute sounds and vibrations during video recording. */
139 private AudioManager mAudioManager;
141 * The ringer mode that was set when video recording started. We use this to
142 * reset the mode once video recording has stopped.
144 private int mOriginalRingerMode;
146 private boolean mSwitchingCamera;
147 private boolean mMediaRecorderRecording = false;
148 private long mRecordingStartTime;
149 private boolean mRecordingTimeCountsDown = false;
150 private long mOnResumeTime;
151 // The video file that the hardware camera is about to record into
152 // (or is recording into.
153 private String mVideoFilename;
154 private ParcelFileDescriptor mVideoFileDescriptor;
156 // The video file that has already been recorded, and that is being
157 // examined by the user.
158 private String mCurrentVideoFilename;
159 private Uri mCurrentVideoUri;
160 private boolean mCurrentVideoUriFromMediaSaved;
161 private ContentValues mCurrentVideoValues;
163 private CamcorderProfile mProfile;
165 // The video duration limit. 0 means no limit.
166 private int mMaxVideoDurationInMs;
168 boolean mPreviewing = false; // True if preview is started.
169 // The display rotation in degrees. This is only valid when mPreviewing is
171 private int mDisplayRotation;
172 private int mCameraDisplayOrientation;
173 private AppController mAppController;
175 private int mDesiredPreviewWidth;
176 private int mDesiredPreviewHeight;
177 private ContentResolver mContentResolver;
179 private LocationManager mLocationManager;
181 private int mPendingSwitchCameraId;
182 private final Handler mHandler = new MainHandler();
184 private CameraProxy mCameraDevice;
186 private float mZoomValue; // The current zoom ratio.
188 private final MediaSaver.OnMediaSavedListener mOnVideoSavedListener =
189 new MediaSaver.OnMediaSavedListener() {
191 public void onMediaSaved(Uri uri) {
193 mCurrentVideoUri = uri;
194 mCurrentVideoUriFromMediaSaved = true;
196 mActivity.notifyNewMedia(uri);
201 private final MediaSaver.OnMediaSavedListener mOnPhotoSavedListener =
202 new MediaSaver.OnMediaSavedListener() {
204 public void onMediaSaved(Uri uri) {
206 mActivity.notifyNewMedia(uri);
210 private FocusOverlayManager mFocusManager;
211 private boolean mMirror;
212 private boolean mFocusAreaSupported;
213 private boolean mMeteringAreaSupported;
215 private final CameraAgent.CameraAFCallback mAutoFocusCallback =
216 new CameraAgent.CameraAFCallback() {
218 public void onAutoFocus(boolean focused, CameraProxy camera) {
222 mFocusManager.onAutoFocus(focused, false);
226 private final Object mAutoFocusMoveCallback =
227 ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
228 ? new CameraAgent.CameraAFMoveCallback() {
230 public void onAutoFocusMoving(boolean moving, CameraProxy camera) {
231 mFocusManager.onAutoFocusMoving(moving);
236 * This Handler is used to post message back onto the main thread of the
239 private class MainHandler extends Handler {
241 public void handleMessage(Message msg) {
244 case MSG_ENABLE_SHUTTER_BUTTON:
245 mAppController.setShutterEnabled(true);
248 case MSG_UPDATE_RECORD_TIME: {
249 updateRecordingTime();
253 case MSG_CHECK_DISPLAY_ROTATION: {
254 // Restart the preview if display rotation has changed.
255 // Sometimes this happens when the device is held upside
256 // down and camera app is opened. Rotation animation will
257 // take some time and the rotation value we have got may be
258 // wrong. Framework does not have a callback for this now.
259 if ((CameraUtil.getDisplayRotation() != mDisplayRotation)
260 && !mMediaRecorderRecording && !mSwitchingCamera) {
263 if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
264 mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100);
269 case MSG_SWITCH_CAMERA: {
274 case MSG_SWITCH_CAMERA_START_ANIMATION: {
276 //((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
278 // Enable all camera controls.
279 mSwitchingCamera = false;
284 Log.v(TAG, "Unhandled message: " + msg.what);
290 private BroadcastReceiver mReceiver = null;
292 private class MyBroadcastReceiver extends BroadcastReceiver {
294 public void onReceive(Context context, Intent intent) {
295 String action = intent.getAction();
296 if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
297 stopVideoRecording();
298 } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
299 Toast.makeText(mActivity,
300 mActivity.getResources().getString(R.string.wait), Toast.LENGTH_LONG).show();
305 private int mShutterIconId;
309 * Construct a new video module.
311 public VideoModule(AppController app) {
316 public String getPeekAccessibilityString() {
317 return mAppController.getAndroidContext()
318 .getResources().getString(R.string.video_accessibility_peek);
321 private String createName(long dateTaken) {
322 Date date = new Date(dateTaken);
323 SimpleDateFormat dateFormat = new SimpleDateFormat(
324 mActivity.getString(R.string.video_file_name_format));
326 return dateFormat.format(date);
330 public void init(CameraActivity activity, boolean isSecureCamera, boolean isCaptureIntent) {
331 mActivity = activity;
332 // TODO: Need to look at the controller interface to see if we can get
333 // rid of passing in the activity directly.
334 mAppController = mActivity;
335 mAudioManager = AndroidServices.instance().provideAudioManager();
337 mActivity.updateStorageSpaceAndHint(null);
339 mUI = new VideoUI(mActivity, this, mActivity.getModuleLayoutRoot());
340 mActivity.setPreviewStatusListener(mUI);
342 SettingsManager settingsManager = mActivity.getSettingsManager();
343 mCameraId = settingsManager.getInteger(mAppController.getModuleScope(),
347 * To reduce startup time, we start the preview in another thread.
348 * We make sure the preview is started at the end of onCreate.
350 requestCamera(mCameraId);
352 mContentResolver = mActivity.getContentResolver();
354 // Surface texture is from camera screen nail and startPreview needs it.
355 // This must be done before startPreview.
356 mIsVideoCaptureIntent = isVideoCaptureIntent();
358 mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
359 mLocationManager = mActivity.getLocationManager();
361 mUI.setOrientationIndicator(0, false);
362 setDisplayOrientation();
364 mPendingSwitchCameraId = -1;
366 mShutterIconId = CameraUtil.getCameraShutterIconId(
367 mAppController.getCurrentModuleIndex(), mAppController.getAndroidContext());
371 public boolean isUsingBottomBar() {
375 private void initializeControlByIntent() {
376 if (isVideoCaptureIntent()) {
377 if (!mDontResetIntentUiOnResume) {
378 mActivity.getCameraAppUI().transitionToIntentCaptureLayout();
381 mDontResetIntentUiOnResume = false;
386 public void onSingleTapUp(View view, int x, int y) {
387 if (mPaused || mCameraDevice == null) {
390 if (mMediaRecorderRecording) {
391 if (!mSnapshotInProgress) {
396 // Check if metering area or focus area is supported.
397 if (!mFocusAreaSupported && !mMeteringAreaSupported) {
401 mFocusManager.onSingleTapUp(x, y);
404 private void takeASnapshot() {
405 // Only take snapshots if video snapshot is supported by device
406 if(!mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT)) {
407 Log.w(TAG, "Cannot take a video snapshot - not supported by hardware");
410 if (!mIsVideoCaptureIntent) {
411 if (!mMediaRecorderRecording || mPaused || mSnapshotInProgress
412 || !mAppController.isShutterEnabled() || mCameraDevice == null) {
416 Location loc = mLocationManager.getCurrentLocation();
417 CameraUtil.setGpsParameters(mCameraSettings, loc);
418 mCameraDevice.applySettings(mCameraSettings);
420 Log.i(TAG, "Video snapshot start");
421 mCameraDevice.takePicture(mHandler,
422 null, null, null, new JpegPictureCallback(loc));
423 showVideoSnapshotUI(true);
424 mSnapshotInProgress = true;
428 private void updateAutoFocusMoveCallback() {
429 if (mPaused || mCameraDevice == null) {
433 if (mCameraSettings.getCurrentFocusMode() == CameraCapabilities.FocusMode.CONTINUOUS_PICTURE) {
434 mCameraDevice.setAutoFocusMoveCallback(mHandler,
435 (CameraAgent.CameraAFMoveCallback) mAutoFocusMoveCallback);
437 mCameraDevice.setAutoFocusMoveCallback(null, null);
442 * @return Whether the currently active camera is front-facing.
444 private boolean isCameraFrontFacing() {
445 return mAppController.getCameraProvider().getCharacteristics(mCameraId)
450 * @return Whether the currently active camera is back-facing.
452 private boolean isCameraBackFacing() {
453 return mAppController.getCameraProvider().getCharacteristics(mCameraId)
458 * The focus manager gets initialized after camera is available.
460 private void initializeFocusManager() {
461 // Create FocusManager object. startPreview needs it.
462 // if mFocusManager not null, reuse it
463 // otherwise create a new instance
464 if (mFocusManager != null) {
465 mFocusManager.removeMessages();
467 mMirror = isCameraFrontFacing();
468 String[] defaultFocusModesStrings = mActivity.getResources().getStringArray(
469 R.array.pref_camera_focusmode_default_array);
470 CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier();
471 ArrayList<CameraCapabilities.FocusMode> defaultFocusModes =
472 new ArrayList<CameraCapabilities.FocusMode>();
473 for (String modeString : defaultFocusModesStrings) {
474 CameraCapabilities.FocusMode mode = stringifier.focusModeFromString(modeString);
476 defaultFocusModes.add(mode);
479 mFocusManager = new FocusOverlayManager(mAppController,
480 defaultFocusModes, mCameraCapabilities, this, mMirror,
481 mActivity.getMainLooper(), mUI.getFocusRing());
483 mAppController.addPreviewAreaSizeChangedListener(mFocusManager);
487 public void onOrientationChanged(OrientationManager orientationManager,
488 OrientationManager.DeviceOrientation deviceOrientation) {
489 mUI.onOrientationChanged(orientationManager, deviceOrientation);
492 private final ButtonManager.ButtonCallback mFlashCallback =
493 new ButtonManager.ButtonCallback() {
495 public void onStateChanged(int state) {
499 // Update flash parameters.
500 enableTorchMode(true);
504 private final ButtonManager.ButtonCallback mCameraCallback =
505 new ButtonManager.ButtonCallback() {
507 public void onStateChanged(int state) {
508 if (mPaused || mAppController.getCameraProvider().waitingForCamera()) {
511 ButtonManager buttonManager = mActivity.getButtonManager();
512 buttonManager.disableCameraButtonAndBlock();
513 mPendingSwitchCameraId = state;
514 Log.d(TAG, "Start to copy texture.");
516 // Disable all camera controls.
517 mSwitchingCamera = true;
522 private final View.OnClickListener mCancelCallback = new View.OnClickListener() {
524 public void onClick(View v) {
525 onReviewCancelClicked(v);
529 private final View.OnClickListener mDoneCallback = new View.OnClickListener() {
531 public void onClick(View v) {
532 onReviewDoneClicked(v);
535 private final View.OnClickListener mReviewCallback = new View.OnClickListener() {
537 public void onClick(View v) {
538 onReviewPlayClicked(v);
543 public void hardResetSettings(SettingsManager settingsManager) {
544 // VideoModule does not need to hard reset any settings.
548 public HardwareSpec getHardwareSpec() {
549 if (mHardwareSpec == null) {
550 mHardwareSpec = (mCameraSettings != null ?
551 new HardwareSpecImpl(getCameraProvider(), mCameraCapabilities,
552 mAppController.getCameraFeatureConfig(), isCameraFrontFacing()) : null);
554 return mHardwareSpec;
558 public CameraAppUI.BottomBarUISpec getBottomBarSpec() {
559 CameraAppUI.BottomBarUISpec bottomBarSpec = new CameraAppUI.BottomBarUISpec();
561 bottomBarSpec.enableCamera = true;
562 bottomBarSpec.cameraCallback = mCameraCallback;
563 bottomBarSpec.enableTorchFlash = true;
564 bottomBarSpec.flashCallback = mFlashCallback;
565 bottomBarSpec.hideHdr = true;
566 bottomBarSpec.enableGridLines = true;
567 bottomBarSpec.enableExposureCompensation = false;
568 bottomBarSpec.isExposureCompensationSupported = false;
570 if (isVideoCaptureIntent()) {
571 bottomBarSpec.showCancel = true;
572 bottomBarSpec.cancelCallback = mCancelCallback;
573 bottomBarSpec.showDone = true;
574 bottomBarSpec.doneCallback = mDoneCallback;
575 bottomBarSpec.showReview = true;
576 bottomBarSpec.reviewCallback = mReviewCallback;
579 return bottomBarSpec;
583 public void onCameraAvailable(CameraProxy cameraProxy) {
584 if (cameraProxy == null) {
585 Log.w(TAG, "onCameraAvailable returns a null CameraProxy object");
588 mCameraDevice = cameraProxy;
589 mCameraCapabilities = mCameraDevice.getCapabilities();
590 mAppController.getCameraAppUI().showAccessibilityZoomUI(
591 mCameraCapabilities.getMaxZoomRatio());
592 mCameraSettings = mCameraDevice.getSettings();
593 mFocusAreaSupported = mCameraCapabilities.supports(CameraCapabilities.Feature.FOCUS_AREA);
594 mMeteringAreaSupported =
595 mCameraCapabilities.supports(CameraCapabilities.Feature.METERING_AREA);
596 readVideoPreferences();
597 updateDesiredPreviewSize();
598 resizeForPreviewAspectRatio();
599 initializeFocusManager();
600 // TODO: Having focus overlay manager caching the parameters is prone to error,
601 // we should consider passing the parameters to focus overlay to ensure the
602 // parameters are up to date.
603 mFocusManager.updateCapabilities(mCameraCapabilities);
606 initializeVideoSnapshot();
607 mUI.initializeZoom(mCameraSettings, mCameraCapabilities);
608 initializeControlByIntent();
610 mHardwareSpec = new HardwareSpecImpl(getCameraProvider(), mCameraCapabilities,
611 mAppController.getCameraFeatureConfig(), isCameraFrontFacing());
613 ButtonManager buttonManager = mActivity.getButtonManager();
614 buttonManager.enableCameraButton();
617 private void startPlayVideoActivity() {
618 Intent intent = new Intent(Intent.ACTION_VIEW);
619 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
620 intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat));
622 mActivity.launchActivityByIntent(intent);
623 } catch (ActivityNotFoundException ex) {
624 Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex);
629 public void onReviewPlayClicked(View v) {
630 startPlayVideoActivity();
634 public void onReviewDoneClicked(View v) {
635 mIsInReviewMode = false;
636 doReturnToCaller(true);
640 public void onReviewCancelClicked(View v) {
641 // TODO: It should be better to not even insert the URI at all before we
642 // confirm done in review, which means we need to handle temporary video
643 // files in a quite different way than we currently had.
644 // Make sure we don't delete the Uri sent from the video capture intent.
645 if (mCurrentVideoUriFromMediaSaved) {
646 mContentResolver.delete(mCurrentVideoUri, null, null);
648 mIsInReviewMode = false;
649 doReturnToCaller(false);
653 public boolean isInReviewMode() {
654 return mIsInReviewMode;
657 private void onStopVideoRecording() {
658 mAppController.getCameraAppUI().setSwipeEnabled(true);
659 boolean recordFail = stopVideoRecording();
660 if (mIsVideoCaptureIntent) {
662 doReturnToCaller(!recordFail);
663 } else if (!recordFail) {
666 } else if (!recordFail){
667 // Start capture animation.
668 if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
669 // The capture animation is disabled on ICS because we use SurfaceView
670 // for preview during recording. When the recording is done, we switch
671 // back to use SurfaceTexture for preview and we need to stop then start
672 // the preview. This will cause the preview flicker since the preview
673 // will not be continuous for a short period of time.
674 mAppController.startFlashAnimation(false);
679 public void onVideoSaved() {
680 if (mIsVideoCaptureIntent) {
685 public void onProtectiveCurtainClick(View v) {
690 public void onShutterButtonClick() {
691 if (mSwitchingCamera) {
694 boolean stop = mMediaRecorderRecording;
697 // CameraAppUI mishandles mode option enable/disable
698 // for video, override that
699 mAppController.getCameraAppUI().enableModeOptions();
700 onStopVideoRecording();
702 // CameraAppUI mishandles mode option enable/disable
703 // for video, override that
704 mAppController.getCameraAppUI().disableModeOptions();
705 startVideoRecording();
707 mAppController.setShutterEnabled(false);
708 if (mCameraSettings != null) {
709 mFocusManager.onShutterUp(mCameraSettings.getCurrentFocusMode());
712 // Keep the shutter button disabled when in video capture intent
713 // mode and recording is stopped. It'll be re-enabled when
714 // re-take button is clicked.
715 if (!(mIsVideoCaptureIntent && stop)) {
716 mHandler.sendEmptyMessageDelayed(MSG_ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT);
721 public void onShutterCoordinate(TouchCoordinate coord) {
726 public void onShutterButtonFocus(boolean pressed) {
727 // TODO: Remove this when old camera controls are removed from the UI.
730 private void readVideoPreferences() {
731 // The preference stores values from ListPreference and is thus string type for all values.
732 // We need to convert it to int manually.
733 SettingsManager settingsManager = mActivity.getSettingsManager();
734 String videoQualityKey = isCameraFrontFacing() ? Keys.KEY_VIDEO_QUALITY_FRONT
735 : Keys.KEY_VIDEO_QUALITY_BACK;
736 String videoQuality = settingsManager
737 .getString(SettingsManager.SCOPE_GLOBAL, videoQualityKey);
738 int quality = SettingsUtil.getVideoQuality(videoQuality, mCameraId);
739 Log.d(TAG, "Selected video quality for '" + videoQuality + "' is " + quality);
741 // Set video quality.
742 Intent intent = mActivity.getIntent();
743 if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
744 int extraVideoQuality =
745 intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
746 if (extraVideoQuality > 0) {
747 quality = CamcorderProfile.QUALITY_HIGH;
748 } else { // 0 is mms.
749 quality = CamcorderProfile.QUALITY_LOW;
753 // Set video duration limit. The limit is read from the preference,
754 // unless it is specified in the intent.
755 if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
757 intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0);
758 mMaxVideoDurationInMs = 1000 * seconds;
760 mMaxVideoDurationInMs = SettingsUtil.getMaxVideoDuration(mActivity
761 .getAndroidContext());
764 // If quality is not supported, request QUALITY_HIGH which is always supported.
765 if (CamcorderProfile.hasProfile(mCameraId, quality) == false) {
766 quality = CamcorderProfile.QUALITY_HIGH;
768 mProfile = CamcorderProfile.get(mCameraId, quality);
769 mPreferenceRead = true;
773 * Calculates and sets local class variables for Desired Preview sizes.
774 * This function should be called after every change in preview camera
775 * resolution and/or before the preview starts. Note that these values still
776 * need to be pushed to the CameraSettings to actually change the preview
777 * resolution. Does nothing when camera pointer is null.
779 private void updateDesiredPreviewSize() {
780 if (mCameraDevice == null) {
784 mCameraSettings = mCameraDevice.getSettings();
785 Point desiredPreviewSize = getDesiredPreviewSize(
786 mCameraCapabilities, mProfile, mUI.getPreviewScreenSize());
787 mDesiredPreviewWidth = desiredPreviewSize.x;
788 mDesiredPreviewHeight = desiredPreviewSize.y;
789 mUI.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
790 Log.v(TAG, "Updated DesiredPreview=" + mDesiredPreviewWidth + "x"
791 + mDesiredPreviewHeight);
795 * Calculates the preview size and stores it in mDesiredPreviewWidth and
796 * mDesiredPreviewHeight.
798 * <p>This function checks {@link
799 * com.android.camera.cameradevice.CameraCapabilities#getPreferredPreviewSizeForVideo()}
800 * but also considers the current preview area size on screen and make sure
801 * the final preview size will not be smaller than 1/2 of the current
802 * on screen preview area in terms of their short sides. This function has
803 * highest priority of WYSIWYG, 1:1 matching as its best match, even if
804 * there's a larger preview that meets the condition above. </p>
806 * @return The preferred preview size or {@code null} if the camera is not
809 private static Point getDesiredPreviewSize(CameraCapabilities capabilities,
810 CamcorderProfile profile, Point previewScreenSize) {
811 if (capabilities.getSupportedVideoSizes() == null) {
812 // Driver doesn't support separate outputs for preview and video.
813 return new Point(profile.videoFrameWidth, profile.videoFrameHeight);
816 final int previewScreenShortSide = (previewScreenSize.x < previewScreenSize.y ?
817 previewScreenSize.x : previewScreenSize.y);
818 List<Size> sizes = Size.convert(capabilities.getSupportedPreviewSizes());
819 Size preferred = new Size(capabilities.getPreferredPreviewSizeForVideo());
820 final int preferredPreviewSizeShortSide = (preferred.width() < preferred.height() ?
821 preferred.width() : preferred.height());
822 if (preferredPreviewSizeShortSide * 2 < previewScreenShortSide) {
823 preferred = new Size(profile.videoFrameWidth, profile.videoFrameHeight);
825 int product = preferred.width() * preferred.height();
826 Iterator<Size> it = sizes.iterator();
827 // Remove the preview sizes that are not preferred.
828 while (it.hasNext()) {
829 Size size = it.next();
830 if (size.width() * size.height() > product) {
835 // Take highest priority for WYSIWYG when the preview exactly matches
836 // video frame size. The variable sizes is assumed to be filtered
837 // for sizes beyond the UI size.
838 for (Size size : sizes) {
839 if (size.width() == profile.videoFrameWidth
840 && size.height() == profile.videoFrameHeight) {
841 Log.v(TAG, "Selected =" + size.width() + "x" + size.height()
842 + " on WYSIWYG Priority");
843 return new Point(profile.videoFrameWidth, profile.videoFrameHeight);
847 Size optimalSize = CameraUtil.getOptimalPreviewSize(sizes,
848 (double) profile.videoFrameWidth / profile.videoFrameHeight);
849 return new Point(optimalSize.width(), optimalSize.height());
852 private void resizeForPreviewAspectRatio() {
853 mUI.setAspectRatio((float) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
856 private void installIntentFilter() {
857 // install an intent filter to receive SD card related events.
858 IntentFilter intentFilter =
859 new IntentFilter(Intent.ACTION_MEDIA_EJECT);
860 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
861 intentFilter.addDataScheme("file");
862 mReceiver = new MyBroadcastReceiver();
863 mActivity.registerReceiver(mReceiver, intentFilter);
866 private void setDisplayOrientation() {
867 mDisplayRotation = CameraUtil.getDisplayRotation();
868 Characteristics info =
869 mActivity.getCameraProvider().getCharacteristics(mCameraId);
870 mCameraDisplayOrientation = info.getPreviewOrientation(mDisplayRotation);
871 // Change the camera display orientation
872 if (mCameraDevice != null) {
873 mCameraDevice.setDisplayOrientation(mDisplayRotation);
875 if (mFocusManager != null) {
876 mFocusManager.setDisplayOrientation(mCameraDisplayOrientation);
881 public void updateCameraOrientation() {
882 if (mMediaRecorderRecording) {
885 if (mDisplayRotation != CameraUtil.getDisplayRotation()) {
886 setDisplayOrientation();
891 public void updatePreviewAspectRatio(float aspectRatio) {
892 mAppController.updatePreviewAspectRatio(aspectRatio);
896 * Returns current Zoom value, with 1.0 as the value for no zoom.
898 private float currentZoomValue() {
899 return mCameraSettings.getCurrentZoomRatio();
903 public void onZoomChanged(float ratio) {
904 // Not useful to change zoom value when the activity is paused.
909 if (mCameraSettings == null || mCameraDevice == null) {
912 // Set zoom parameters asynchronously
913 mCameraSettings.setZoomRatio(mZoomValue);
914 mCameraDevice.applySettings(mCameraSettings);
917 private void startPreview() {
918 Log.i(TAG, "startPreview");
920 SurfaceTexture surfaceTexture = mActivity.getCameraAppUI().getSurfaceTexture();
921 if (!mPreferenceRead || surfaceTexture == null || mPaused == true ||
922 mCameraDevice == null) {
926 if (mPreviewing == true) {
930 setDisplayOrientation();
931 mCameraDevice.setDisplayOrientation(mDisplayRotation);
932 setCameraParameters();
934 if (mFocusManager != null) {
935 // If the focus mode is continuous autofocus, call cancelAutoFocus
936 // to resume it because it may have been paused by autoFocus call.
937 CameraCapabilities.FocusMode focusMode =
938 mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode());
939 if (focusMode == CameraCapabilities.FocusMode.CONTINUOUS_PICTURE) {
940 mCameraDevice.cancelAutoFocus();
944 // This is to notify app controller that preview will start next, so app
945 // controller can set preview callbacks if needed. This has to happen before
946 // preview is started as a workaround of the framework issue related to preview
947 // callbacks that causes preview stretch and crash. (More details see b/12210027
948 // and b/12591410. Don't apply this to L, see b/16649297.
949 if (!ApiHelper.isLOrHigher()) {
950 Log.v(TAG, "calling onPreviewReadyToStart to set one shot callback");
951 mAppController.onPreviewReadyToStart();
953 Log.v(TAG, "on L, no one shot callback necessary");
956 mCameraDevice.setPreviewTexture(surfaceTexture);
957 mCameraDevice.startPreviewWithCallback(new Handler(Looper.getMainLooper()),
958 new CameraAgent.CameraStartPreviewCallback() {
960 public void onPreviewStarted() {
961 VideoModule.this.onPreviewStarted();
965 } catch (Throwable ex) {
967 throw new RuntimeException("startPreview failed", ex);
971 private void onPreviewStarted() {
972 mAppController.setShutterEnabled(true);
973 mAppController.onPreviewStarted();
974 if (mFocusManager != null) {
975 mFocusManager.onPreviewStarted();
980 public void onPreviewInitialDataReceived() {
984 public void stopPreview() {
986 Log.v(TAG, "Skip stopPreview since it's not mPreviewing");
989 if (mCameraDevice == null) {
990 Log.v(TAG, "Skip stopPreview since mCameraDevice is null");
994 Log.v(TAG, "stopPreview");
995 mCameraDevice.stopPreview();
996 if (mFocusManager != null) {
997 mFocusManager.onPreviewStopped();
1002 private void closeCamera() {
1003 Log.i(TAG, "closeCamera");
1004 if (mCameraDevice == null) {
1005 Log.d(TAG, "already stopped.");
1008 mCameraDevice.setZoomChangeListener(null);
1009 mActivity.getCameraProvider().releaseCamera(mCameraDevice.getCameraId());
1010 mCameraDevice = null;
1011 mPreviewing = false;
1012 mSnapshotInProgress = false;
1013 if (mFocusManager != null) {
1014 mFocusManager.onCameraReleased();
1019 public boolean onBackPressed() {
1023 if (mMediaRecorderRecording) {
1024 onStopVideoRecording();
1032 public boolean onKeyDown(int keyCode, KeyEvent event) {
1033 // Do not handle any key if the activity is paused.
1039 case KeyEvent.KEYCODE_CAMERA:
1040 if (event.getRepeatCount() == 0) {
1041 onShutterButtonClick();
1044 case KeyEvent.KEYCODE_DPAD_CENTER:
1045 if (event.getRepeatCount() == 0) {
1046 onShutterButtonClick();
1049 case KeyEvent.KEYCODE_MENU:
1050 // Consume menu button presses during capture.
1051 return mMediaRecorderRecording;
1057 public boolean onKeyUp(int keyCode, KeyEvent event) {
1059 case KeyEvent.KEYCODE_CAMERA:
1060 onShutterButtonClick();
1062 case KeyEvent.KEYCODE_MENU:
1063 // Consume menu button presses during capture.
1064 return mMediaRecorderRecording;
1070 public boolean isVideoCaptureIntent() {
1071 String action = mActivity.getIntent().getAction();
1072 return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action));
1075 private void doReturnToCaller(boolean valid) {
1076 Intent resultIntent = new Intent();
1079 resultCode = Activity.RESULT_OK;
1080 resultIntent.setData(mCurrentVideoUri);
1081 resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1083 resultCode = Activity.RESULT_CANCELED;
1085 mActivity.setResultEx(resultCode, resultIntent);
1089 private void cleanupEmptyFile() {
1090 if (mVideoFilename != null) {
1091 File f = new File(mVideoFilename);
1092 if (f.length() == 0 && f.delete()) {
1093 Log.v(TAG, "Empty video file deleted: " + mVideoFilename);
1094 mVideoFilename = null;
1099 // Prepares media recorder.
1100 private void initializeRecorder() {
1101 Log.i(TAG, "initializeRecorder: " + Thread.currentThread());
1102 // If the mCameraDevice is null, then this activity is going to finish
1103 if (mCameraDevice == null) {
1104 Log.w(TAG, "null camera proxy, not recording");
1107 Intent intent = mActivity.getIntent();
1108 Bundle myExtras = intent.getExtras();
1110 long requestedSizeLimit = 0;
1111 closeVideoFileDescriptor();
1112 mCurrentVideoUriFromMediaSaved = false;
1113 if (mIsVideoCaptureIntent && myExtras != null) {
1114 Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1115 if (saveUri != null) {
1117 mVideoFileDescriptor =
1118 mContentResolver.openFileDescriptor(saveUri, "rw");
1119 mCurrentVideoUri = saveUri;
1120 } catch (java.io.FileNotFoundException ex) {
1122 Log.e(TAG, ex.toString());
1125 requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
1127 mMediaRecorder = new MediaRecorder();
1128 // Unlock the camera object before passing it to media recorder.
1129 mCameraDevice.unlock();
1130 // We rely here on the fact that the unlock call above is synchronous
1131 // and blocks until it occurs in the handler thread. Thereby ensuring
1132 // that we are up to date with handler requests, and if this proxy had
1133 // ever been released by a prior command, it would be null.
1134 Camera camera = mCameraDevice.getCamera();
1135 // If the camera device is null, the camera proxy is stale and recording
1136 // should be ignored.
1137 if (camera == null) {
1138 Log.w(TAG, "null camera within proxy, not recording");
1142 mMediaRecorder.setCamera(camera);
1143 mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
1144 mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
1145 mMediaRecorder.setProfile(mProfile);
1146 mMediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
1147 mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs);
1149 setRecordLocation();
1152 // Try Uri in the intent first. If it doesn't exist, use our own
1154 if (mVideoFileDescriptor != null) {
1155 mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
1157 generateVideoFilename(mProfile.fileFormat);
1158 mMediaRecorder.setOutputFile(mVideoFilename);
1161 // Set maximum file size.
1162 long maxFileSize = mActivity.getStorageSpaceBytes() - Storage.LOW_STORAGE_THRESHOLD_BYTES;
1163 if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
1164 maxFileSize = requestedSizeLimit;
1168 mMediaRecorder.setMaxFileSize(maxFileSize);
1169 } catch (RuntimeException exception) {
1170 // We are going to ignore failure of setMaxFileSize here, as
1171 // a) The composer selected may simply not support it, or
1172 // b) The underlying media framework may not handle 64-bit range
1173 // on the size restriction.
1176 int sensorOrientation =
1177 mActivity.getCameraProvider().getCharacteristics(mCameraId).getSensorOrientation();
1178 int deviceOrientation =
1179 mAppController.getOrientationManager().getDeviceOrientation().getDegrees();
1180 int rotation = CameraUtil.getImageRotation(
1181 sensorOrientation, deviceOrientation, isCameraFrontFacing());
1182 mMediaRecorder.setOrientationHint(rotation);
1185 mMediaRecorder.prepare();
1186 } catch (IOException e) {
1187 Log.e(TAG, "prepare failed for " + mVideoFilename, e);
1188 releaseMediaRecorder();
1189 throw new RuntimeException(e);
1192 mMediaRecorder.setOnErrorListener(this);
1193 mMediaRecorder.setOnInfoListener(this);
1196 private static void setCaptureRate(MediaRecorder recorder, double fps) {
1197 recorder.setCaptureRate(fps);
1200 private void setRecordLocation() {
1201 Location loc = mLocationManager.getCurrentLocation();
1203 mMediaRecorder.setLocation((float) loc.getLatitude(),
1204 (float) loc.getLongitude());
1208 private void releaseMediaRecorder() {
1209 Log.i(TAG, "Releasing media recorder.");
1210 if (mMediaRecorder != null) {
1212 mMediaRecorder.reset();
1213 mMediaRecorder.release();
1214 mMediaRecorder = null;
1216 mVideoFilename = null;
1219 private void generateVideoFilename(int outputFileFormat) {
1220 long dateTaken = System.currentTimeMillis();
1221 String title = createName(dateTaken);
1222 // Used when emailing.
1223 String filename = title + convertOutputFormatToFileExt(outputFileFormat);
1224 String mime = convertOutputFormatToMimeType(outputFileFormat);
1225 String path = Storage.DIRECTORY + '/' + filename;
1226 String tmpPath = path + ".tmp";
1227 mCurrentVideoValues = new ContentValues(9);
1228 mCurrentVideoValues.put(Video.Media.TITLE, title);
1229 mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename);
1230 mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken);
1231 mCurrentVideoValues.put(MediaColumns.DATE_MODIFIED, dateTaken / 1000);
1232 mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime);
1233 mCurrentVideoValues.put(Video.Media.DATA, path);
1234 mCurrentVideoValues.put(Video.Media.WIDTH, mProfile.videoFrameWidth);
1235 mCurrentVideoValues.put(Video.Media.HEIGHT, mProfile.videoFrameHeight);
1236 mCurrentVideoValues.put(Video.Media.RESOLUTION,
1237 Integer.toString(mProfile.videoFrameWidth) + "x" +
1238 Integer.toString(mProfile.videoFrameHeight));
1239 Location loc = mLocationManager.getCurrentLocation();
1241 mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude());
1242 mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude());
1244 mVideoFilename = tmpPath;
1245 Log.v(TAG, "New video filename: " + mVideoFilename);
1248 private void logVideoCapture(long duration) {
1249 String flashSetting = mActivity.getSettingsManager()
1250 .getString(mAppController.getCameraScope(),
1251 Keys.KEY_VIDEOCAMERA_FLASH_MODE);
1252 boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager());
1253 int width = (Integer) mCurrentVideoValues.get(Video.Media.WIDTH);
1254 int height = (Integer) mCurrentVideoValues.get(Video.Media.HEIGHT);
1255 long size = new File(mCurrentVideoFilename).length();
1256 String name = new File(mCurrentVideoValues.getAsString(Video.Media.DATA)).getName();
1257 UsageStatistics.instance().videoCaptureDoneEvent(name, duration, isCameraFrontFacing(),
1258 currentZoomValue(), width, height, size, flashSetting, gridLinesOn);
1261 private void saveVideo() {
1262 if (mVideoFileDescriptor == null) {
1263 long duration = SystemClock.uptimeMillis() - mRecordingStartTime;
1267 Log.w(TAG, "Video duration <= 0 : " + duration);
1269 mCurrentVideoValues.put(Video.Media.SIZE, new File(mCurrentVideoFilename).length());
1270 mCurrentVideoValues.put(Video.Media.DURATION, duration);
1271 getServices().getMediaSaver().addVideo(mCurrentVideoFilename,
1272 mCurrentVideoValues, mOnVideoSavedListener);
1273 logVideoCapture(duration);
1275 mCurrentVideoValues = null;
1278 private void deleteVideoFile(String fileName) {
1279 Log.v(TAG, "Deleting video " + fileName);
1280 File f = new File(fileName);
1282 Log.v(TAG, "Could not delete " + fileName);
1286 // from MediaRecorder.OnErrorListener
1288 public void onError(MediaRecorder mr, int what, int extra) {
1289 Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra);
1290 if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
1291 // We may have run out of space on the sdcard.
1292 stopVideoRecording();
1293 mActivity.updateStorageSpaceAndHint(null);
1297 // from MediaRecorder.OnInfoListener
1299 public void onInfo(MediaRecorder mr, int what, int extra) {
1300 if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
1301 if (mMediaRecorderRecording) {
1302 onStopVideoRecording();
1304 } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
1305 if (mMediaRecorderRecording) {
1306 onStopVideoRecording();
1310 Toast.makeText(mActivity, R.string.video_reach_size_limit,
1311 Toast.LENGTH_LONG).show();
1316 * Make sure we're not recording music playing in the background, ask the
1317 * MediaPlaybackService to pause playback.
1319 private void silenceSoundsAndVibrations() {
1320 // Get the audio focus which causes other music players to stop.
1321 mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC,
1322 AudioManager.AUDIOFOCUS_GAIN);
1323 // Store current ringer mode so we can set it once video recording is
1325 mOriginalRingerMode = mAudioManager.getRingerMode();
1326 // Make sure no system sounds and vibrations happen during video
1329 mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
1330 } catch (SecurityException e) {
1331 Log.e(TAG, "Error: " + e);
1335 private void restoreRingerMode() {
1336 // First check if ringer mode was changed during the recording. If not,
1337 // re-set the mode that was set before video recording started.
1338 if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
1339 // Set the original ringer mode back.
1341 mAudioManager.setRingerMode(mOriginalRingerMode);
1342 } catch (SecurityException e) {
1343 Log.e(TAG, "Error: " + e);
1349 public boolean isRecording() {
1350 return mMediaRecorderRecording;
1353 private void startVideoRecording() {
1354 Log.i(TAG, "startVideoRecording: " + Thread.currentThread());
1355 mUI.cancelAnimations();
1356 mUI.setSwipingEnabled(false);
1357 mUI.hidePassiveFocusIndicator();
1358 mAppController.getCameraAppUI().hideCaptureIndicator();
1359 mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(true);
1361 mActivity.updateStorageSpaceAndHint(new CameraActivity.OnStorageUpdateDoneListener() {
1363 public void onStorageUpdateDone(long bytes) {
1364 if (bytes <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
1365 Log.w(TAG, "Storage issue, ignore the start request");
1367 if (mCameraDevice == null) {
1368 Log.v(TAG, "in storage callback after camera closed");
1371 if (mPaused == true) {
1372 Log.v(TAG, "in storage callback after module paused");
1376 // Monkey is so fast so it could trigger startVideoRecording twice. To prevent
1377 // app crash (b/17313985), do nothing here for the second storage-checking
1378 // callback because recording is already started.
1379 if (mMediaRecorderRecording) {
1380 Log.v(TAG, "in storage callback after recording started");
1384 mCurrentVideoUri = null;
1386 initializeRecorder();
1387 if (mMediaRecorder == null) {
1388 Log.e(TAG, "Fail to initialize media recorder");
1393 mMediaRecorder.start(); // Recording is now started
1394 } catch (RuntimeException e) {
1395 Log.e(TAG, "Could not start media recorder. ", e);
1396 mAppController.getFatalErrorHandler().onGenericCameraAccessFailure();
1397 releaseMediaRecorder();
1398 // If start fails, frameworks will not lock the camera for us.
1399 mCameraDevice.lock();
1402 // Make sure we stop playing sounds and disable the
1403 // vibrations during video recording. Post delayed to avoid
1404 // silencing the recording start sound.
1405 mHandler.postDelayed(new Runnable() {
1408 silenceSoundsAndVibrations();
1412 mAppController.getCameraAppUI().setSwipeEnabled(false);
1414 // The parameters might have been altered by MediaRecorder already.
1415 // We need to force mCameraDevice to refresh before getting it.
1416 mCameraDevice.refreshSettings();
1417 // The parameters may have been changed by MediaRecorder upon starting
1418 // recording. We need to alter the parameters if we support camcorder
1419 // zoom. To reduce latency when setting the parameters during zoom, we
1420 // update the settings here once.
1421 mCameraSettings = mCameraDevice.getSettings();
1423 mMediaRecorderRecording = true;
1424 mActivity.lockOrientation();
1425 mRecordingStartTime = SystemClock.uptimeMillis();
1427 // A special case of mode options closing: during capture it should
1428 // not be possible to change mode state.
1429 mAppController.getCameraAppUI().hideModeOptions();
1430 mAppController.getCameraAppUI().animateBottomBarToVideoStop(R.drawable.ic_stop);
1431 mUI.showRecordingUI(true);
1433 setFocusParameters();
1435 updateRecordingTime();
1436 mActivity.enableKeepScreenOn(true);
1442 private Bitmap getVideoThumbnail() {
1443 Bitmap bitmap = null;
1444 if (mVideoFileDescriptor != null) {
1445 bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
1446 mDesiredPreviewWidth);
1447 } else if (mCurrentVideoUri != null) {
1449 mVideoFileDescriptor = mContentResolver.openFileDescriptor(mCurrentVideoUri, "r");
1450 bitmap = Thumbnail.createVideoThumbnailBitmap(
1451 mVideoFileDescriptor.getFileDescriptor(), mDesiredPreviewWidth);
1452 } catch (java.io.FileNotFoundException ex) {
1454 Log.e(TAG, ex.toString());
1458 if (bitmap != null) {
1459 // MetadataRetriever already rotates the thumbnail. We should rotate
1460 // it to match the UI orientation (and mirror if it is front-facing camera).
1461 bitmap = CameraUtil.rotateAndMirror(bitmap, 0, isCameraFrontFacing());
1466 private void showCaptureResult() {
1467 mIsInReviewMode = true;
1468 Bitmap bitmap = getVideoThumbnail();
1469 if (bitmap != null) {
1470 mUI.showReviewImage(bitmap);
1472 mUI.showReviewControls();
1475 private boolean stopVideoRecording() {
1476 // Do nothing if camera device is still capturing photo. Monkey test can trigger app crashes
1477 // (b/17313985) without this check. Crash could also be reproduced by continuously tapping
1478 // on shutter button and preview with two fingers.
1479 if (mSnapshotInProgress) {
1480 Log.v(TAG, "Skip stopVideoRecording since snapshot in progress");
1483 Log.v(TAG, "stopVideoRecording");
1485 // Re-enable sound as early as possible to avoid interfering with stop
1487 restoreRingerMode();
1489 mUI.setSwipingEnabled(true);
1490 mUI.showPassiveFocusIndicator();
1491 mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(false);
1493 boolean fail = false;
1494 if (mMediaRecorderRecording) {
1495 boolean shouldAddToMediaStoreNow = false;
1498 mMediaRecorder.setOnErrorListener(null);
1499 mMediaRecorder.setOnInfoListener(null);
1500 mMediaRecorder.stop();
1501 shouldAddToMediaStoreNow = true;
1502 mCurrentVideoFilename = mVideoFilename;
1503 Log.v(TAG, "stopVideoRecording: current video filename: " + mCurrentVideoFilename);
1504 } catch (RuntimeException e) {
1505 Log.e(TAG, "stop fail", e);
1506 if (mVideoFilename != null) {
1507 deleteVideoFile(mVideoFilename);
1511 mMediaRecorderRecording = false;
1512 mActivity.unlockOrientation();
1514 // If the activity is paused, this means activity is interrupted
1515 // during recording. Release the camera as soon as possible because
1516 // face unlock or other applications may need to use the camera.
1518 // b/16300704: Monkey is fast so it could pause the module while recording.
1519 // stopPreview should definitely be called before switching off.
1524 mUI.showRecordingUI(false);
1525 // The orientation was fixed during video recording. Now make it
1526 // reflect the device orientation as video recording is stopped.
1527 mUI.setOrientationIndicator(0, true);
1528 mActivity.enableKeepScreenOn(false);
1529 if (shouldAddToMediaStoreNow && !fail) {
1530 if (mVideoFileDescriptor == null) {
1532 } else if (mIsVideoCaptureIntent) {
1533 // if no file save is needed, we can show the post capture UI now
1534 showCaptureResult();
1538 // release media recorder
1539 releaseMediaRecorder();
1541 mAppController.getCameraAppUI().showModeOptions();
1542 mAppController.getCameraAppUI().animateBottomBarToFullSize(mShutterIconId);
1543 if (!mPaused && mCameraDevice != null) {
1544 setFocusParameters();
1545 mCameraDevice.lock();
1546 if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
1548 // Switch back to use SurfaceTexture for preview.
1551 // Update the parameters here because the parameters might have been altered
1552 // by MediaRecorder.
1553 mCameraSettings = mCameraDevice.getSettings();
1556 // Check this in advance of each shot so we don't add to shutter
1557 // latency. It's true that someone else could write to the SD card
1558 // in the mean time and fill it, but that could have happened
1559 // between the shutter press and saving the file too.
1560 mActivity.updateStorageSpaceAndHint(null);
1565 private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
1566 long seconds = milliSeconds / 1000; // round down to compute seconds
1567 long minutes = seconds / 60;
1568 long hours = minutes / 60;
1569 long remainderMinutes = minutes - (hours * 60);
1570 long remainderSeconds = seconds - (minutes * 60);
1572 StringBuilder timeStringBuilder = new StringBuilder();
1577 timeStringBuilder.append('0');
1579 timeStringBuilder.append(hours);
1581 timeStringBuilder.append(':');
1585 if (remainderMinutes < 10) {
1586 timeStringBuilder.append('0');
1588 timeStringBuilder.append(remainderMinutes);
1589 timeStringBuilder.append(':');
1592 if (remainderSeconds < 10) {
1593 timeStringBuilder.append('0');
1595 timeStringBuilder.append(remainderSeconds);
1598 if (displayCentiSeconds) {
1599 timeStringBuilder.append('.');
1600 long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
1601 if (remainderCentiSeconds < 10) {
1602 timeStringBuilder.append('0');
1604 timeStringBuilder.append(remainderCentiSeconds);
1607 return timeStringBuilder.toString();
1610 private void updateRecordingTime() {
1611 if (!mMediaRecorderRecording) {
1614 long now = SystemClock.uptimeMillis();
1615 long delta = now - mRecordingStartTime;
1617 // Starting a minute before reaching the max duration
1618 // limit, we'll countdown the remaining time instead.
1619 boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
1620 && delta >= mMaxVideoDurationInMs - 60000);
1622 long deltaAdjusted = delta;
1623 if (countdownRemainingTime) {
1624 deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
1628 long targetNextUpdateDelay;
1630 text = millisecondToTimeString(deltaAdjusted, false);
1631 targetNextUpdateDelay = 1000;
1633 mUI.setRecordingTime(text);
1635 if (mRecordingTimeCountsDown != countdownRemainingTime) {
1636 // Avoid setting the color on every update, do it only
1637 // when it needs changing.
1638 mRecordingTimeCountsDown = countdownRemainingTime;
1640 int color = mActivity.getResources().getColor(R.color.recording_time_remaining_text);
1642 mUI.setRecordingTimeTextColor(color);
1645 long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
1646 mHandler.sendEmptyMessageDelayed(MSG_UPDATE_RECORD_TIME, actualNextUpdateDelay);
1649 private static boolean isSupported(String value, List<String> supported) {
1650 return supported == null ? false : supported.indexOf(value) >= 0;
1653 @SuppressWarnings("deprecation")
1654 private void setCameraParameters() {
1655 SettingsManager settingsManager = mActivity.getSettingsManager();
1657 // Update Desired Preview size in case video camera resolution has changed.
1658 updateDesiredPreviewSize();
1660 Size previewSize = new Size(mDesiredPreviewWidth, mDesiredPreviewHeight);
1661 mCameraSettings.setPreviewSize(previewSize.toPortabilitySize());
1662 // This is required for Samsung SGH-I337 and probably other Samsung S4 versions
1663 if (Build.BRAND.toLowerCase().contains("samsung")) {
1664 mCameraSettings.setSetting("video-size",
1665 mProfile.videoFrameWidth + "x" + mProfile.videoFrameHeight);
1668 CameraUtil.getMaxPreviewFpsRange(mCameraCapabilities.getSupportedPreviewFpsRange());
1669 if (fpsRange.length > 0) {
1670 mCameraSettings.setPreviewFpsRange(fpsRange[0], fpsRange[1]);
1672 mCameraSettings.setPreviewFrameRate(mProfile.videoFrameRate);
1675 enableTorchMode(Keys.isCameraBackFacing(settingsManager, mAppController.getModuleScope()));
1678 if (mCameraCapabilities.supports(CameraCapabilities.Feature.ZOOM)) {
1679 mCameraSettings.setZoomRatio(mZoomValue);
1681 updateFocusParameters();
1683 mCameraSettings.setRecordingHintEnabled(true);
1685 if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_STABILIZATION)) {
1686 mCameraSettings.setVideoStabilization(true);
1689 // Set picture size.
1690 // The logic here is different from the logic in still-mode camera.
1691 // There we determine the preview size based on the picture size, but
1692 // here we determine the picture size based on the preview size.
1693 List<Size> supported = Size.convert(mCameraCapabilities.getSupportedPhotoSizes());
1694 Size optimalSize = CameraUtil.getOptimalVideoSnapshotPictureSize(supported,
1695 mDesiredPreviewWidth, mDesiredPreviewHeight);
1696 Size original = new Size(mCameraSettings.getCurrentPhotoSize());
1697 if (!original.equals(optimalSize)) {
1698 mCameraSettings.setPhotoSize(optimalSize.toPortabilitySize());
1700 Log.d(TAG, "Video snapshot size is " + optimalSize);
1702 // Set JPEG quality.
1703 int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1704 CameraProfile.QUALITY_HIGH);
1705 mCameraSettings.setPhotoJpegCompressionQuality(jpegQuality);
1707 if (mCameraDevice != null) {
1708 mCameraDevice.applySettings(mCameraSettings);
1709 // Nexus 5 through KitKat 4.4.2 requires a second call to
1710 // .setParameters() for frame rate settings to take effect.
1711 mCameraDevice.applySettings(mCameraSettings);
1714 // Update UI based on the new parameters.
1715 mUI.updateOnScreenIndicators(mCameraSettings);
1718 private void updateFocusParameters() {
1719 // Set continuous autofocus. During recording, we use "continuous-video"
1720 // auto focus mode to ensure smooth focusing. Whereas during preview (i.e.
1721 // before recording starts) we use "continuous-picture" auto focus mode
1722 // for faster but slightly jittery focusing.
1723 Set<CameraCapabilities.FocusMode> supportedFocus = mCameraCapabilities
1724 .getSupportedFocusModes();
1725 if (mMediaRecorderRecording) {
1726 if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO)) {
1727 mCameraSettings.setFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
1728 mFocusManager.overrideFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO);
1730 mFocusManager.overrideFocusMode(null);
1733 // FIXME(b/16984793): This is broken. For some reasons, CONTINUOUS_PICTURE is not on
1734 // when preview starts.
1735 mFocusManager.overrideFocusMode(null);
1736 if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_PICTURE)) {
1737 mCameraSettings.setFocusMode(
1738 mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode()));
1739 if (mFocusAreaSupported) {
1740 mCameraSettings.setFocusAreas(mFocusManager.getFocusAreas());
1744 updateAutoFocusMoveCallback();
1748 public void resume() {
1749 if (isVideoCaptureIntent()) {
1750 mDontResetIntentUiOnResume = mPaused;
1754 installIntentFilter();
1755 mAppController.setShutterEnabled(false);
1758 OrientationManager orientationManager = mAppController.getOrientationManager();
1759 orientationManager.addOnOrientationChangeListener(this);
1760 mUI.onOrientationChanged(orientationManager, orientationManager.getDeviceOrientation());
1762 showVideoSnapshotUI(false);
1765 requestCamera(mCameraId);
1767 // preview already started
1768 mAppController.setShutterEnabled(true);
1771 if (mFocusManager != null) {
1772 // If camera is not open when resume is called, focus manager will not
1773 // be initialized yet, in which case it will start listening to
1774 // preview area size change later in the initialization.
1775 mAppController.addPreviewAreaSizeChangedListener(mFocusManager);
1779 mOnResumeTime = SystemClock.uptimeMillis();
1780 mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100);
1782 getServices().getMemoryManager().addListener(this);
1786 public void pause() {
1789 mAppController.getOrientationManager().removeOnOrientationChangeListener(this);
1791 if (mFocusManager != null) {
1792 // If camera is not open when resume is called, focus manager will not
1793 // be initialized yet, in which case it will start listening to
1794 // preview area size change later in the initialization.
1795 mAppController.removePreviewAreaSizeChangedListener(mFocusManager);
1796 mFocusManager.removeMessages();
1798 if (mMediaRecorderRecording) {
1799 // Camera will be released in onStopVideoRecording.
1800 onStopVideoRecording();
1804 releaseMediaRecorder();
1807 closeVideoFileDescriptor();
1809 if (mReceiver != null) {
1810 mActivity.unregisterReceiver(mReceiver);
1814 mHandler.removeMessages(MSG_CHECK_DISPLAY_ROTATION);
1815 mHandler.removeMessages(MSG_SWITCH_CAMERA);
1816 mHandler.removeMessages(MSG_SWITCH_CAMERA_START_ANIMATION);
1817 mPendingSwitchCameraId = -1;
1818 mSwitchingCamera = false;
1819 mPreferenceRead = false;
1820 getServices().getMemoryManager().removeListener(this);
1825 public void destroy() {
1830 public void onLayoutOrientationChanged(boolean isLandscape) {
1831 setDisplayOrientation();
1834 // TODO: integrate this into the SettingsManager listeners.
1835 public void onSharedPreferenceChanged() {
1839 private void switchCamera() {
1843 SettingsManager settingsManager = mActivity.getSettingsManager();
1845 Log.d(TAG, "Start to switch camera.");
1846 mCameraId = mPendingSwitchCameraId;
1847 mPendingSwitchCameraId = -1;
1848 settingsManager.set(mAppController.getModuleScope(),
1849 Keys.KEY_CAMERA_ID, mCameraId);
1851 if (mFocusManager != null) {
1852 mFocusManager.removeMessages();
1855 requestCamera(mCameraId);
1857 mMirror = isCameraFrontFacing();
1858 if (mFocusManager != null) {
1859 mFocusManager.setMirror(mMirror);
1864 mUI.setOrientationIndicator(0, false);
1866 // Start switch camera animation. Post a message because
1867 // onFrameAvailable from the old camera may already exist.
1868 mHandler.sendEmptyMessage(MSG_SWITCH_CAMERA_START_ANIMATION);
1869 mUI.updateOnScreenIndicators(mCameraSettings);
1872 private void initializeVideoSnapshot() {
1873 if (mCameraSettings == null) {
1878 void showVideoSnapshotUI(boolean enabled) {
1879 if (mCameraSettings == null) {
1882 if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT) &&
1883 !mIsVideoCaptureIntent) {
1885 mAppController.startFlashAnimation(false);
1887 mUI.showPreviewBorder(enabled);
1889 mAppController.setShutterEnabled(!enabled);
1894 * Used to update the flash mode. Video mode can turn on the flash as torch
1895 * mode, which we would like to turn on and off when we switching in and
1896 * out to the preview.
1898 * @param enable Whether torch mode can be enabled.
1900 private void enableTorchMode(boolean enable) {
1901 if (mCameraSettings.getCurrentFlashMode() == null) {
1905 SettingsManager settingsManager = mActivity.getSettingsManager();
1907 CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier();
1908 CameraCapabilities.FlashMode flashMode;
1910 flashMode = stringifier
1911 .flashModeFromString(settingsManager.getString(mAppController.getCameraScope(),
1912 Keys.KEY_VIDEOCAMERA_FLASH_MODE));
1914 flashMode = CameraCapabilities.FlashMode.OFF;
1916 if (mCameraCapabilities.supports(flashMode)) {
1917 mCameraSettings.setFlashMode(flashMode);
1919 /* TODO: Find out how to deal with the following code piece:
1921 flashMode = mCameraSettings.getCurrentFlashMode();
1922 if (flashMode == null) {
1923 flashMode = mActivity.getString(
1924 R.string.pref_camera_flashmode_no_flash);
1925 mParameters.setFlashMode(flashMode);
1928 if (mCameraDevice != null) {
1929 mCameraDevice.applySettings(mCameraSettings);
1931 mUI.updateOnScreenIndicators(mCameraSettings);
1935 public void onPreviewVisibilityChanged(int visibility) {
1937 enableTorchMode(visibility == ModuleController.VISIBILITY_VISIBLE);
1941 private final class JpegPictureCallback implements CameraPictureCallback {
1944 public JpegPictureCallback(Location loc) {
1949 public void onPictureTaken(byte [] jpegData, CameraProxy camera) {
1950 Log.i(TAG, "Video snapshot taken.");
1951 mSnapshotInProgress = false;
1952 showVideoSnapshotUI(false);
1953 storeImage(jpegData, mLocation);
1957 private void storeImage(final byte[] data, Location loc) {
1958 long dateTaken = System.currentTimeMillis();
1959 String title = CameraUtil.instance().createJpegName(dateTaken);
1960 ExifInterface exif = Exif.getExif(data);
1961 int orientation = Exif.getOrientation(exif);
1963 String flashSetting = mActivity.getSettingsManager()
1964 .getString(mAppController.getCameraScope(), Keys.KEY_VIDEOCAMERA_FLASH_MODE);
1965 Boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager());
1966 UsageStatistics.instance().photoCaptureDoneEvent(
1967 eventprotos.NavigationChange.Mode.VIDEO_STILL, title + ".jpeg", exif,
1968 isCameraFrontFacing(), false, currentZoomValue(), flashSetting, gridLinesOn,
1969 null, null, null, null, null, null, null);
1971 getServices().getMediaSaver().addImage(data, title, dateTaken, loc, orientation, exif,
1972 mOnPhotoSavedListener);
1975 private String convertOutputFormatToMimeType(int outputFileFormat) {
1976 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
1979 return "video/3gpp";
1982 private String convertOutputFormatToFileExt(int outputFileFormat) {
1983 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
1989 private void closeVideoFileDescriptor() {
1990 if (mVideoFileDescriptor != null) {
1992 mVideoFileDescriptor.close();
1993 } catch (IOException e) {
1994 Log.e(TAG, "Fail to close fd", e);
1996 mVideoFileDescriptor = null;
2001 public void onPreviewUIReady() {
2006 public void onPreviewUIDestroyed() {
2010 private void requestCamera(int id) {
2011 mActivity.getCameraProvider().requestCamera(id);
2015 public void onMemoryStateChanged(int state) {
2016 mAppController.setShutterEnabled(state == MemoryManager.STATE_OK);
2020 public void onLowMemory() {
2021 // Not much we can do in the video module.
2024 /***********************FocusOverlayManager Listener****************************/
2026 public void autoFocus() {
2027 if (mCameraDevice != null) {
2028 mCameraDevice.autoFocus(mHandler, mAutoFocusCallback);
2033 public void cancelAutoFocus() {
2034 if (mCameraDevice != null) {
2035 mCameraDevice.cancelAutoFocus();
2036 setFocusParameters();
2041 public boolean capture() {
2046 public void startFaceDetection() {
2051 public void stopFaceDetection() {
2056 public void setFocusParameters() {
2057 if (mCameraDevice != null) {
2058 updateFocusParameters();
2059 mCameraDevice.applySettings(mCameraSettings);