1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.camera; 18 19import android.app.Activity; 20import android.content.ActivityNotFoundException; 21import android.content.BroadcastReceiver; 22import android.content.ContentResolver; 23import android.content.ContentValues; 24import android.content.Context; 25import android.content.Intent; 26import android.content.IntentFilter; 27import android.graphics.Bitmap; 28import android.graphics.Point; 29import android.graphics.SurfaceTexture; 30import android.hardware.Camera; 31import android.location.Location; 32import android.media.AudioManager; 33import android.media.CamcorderProfile; 34import android.media.CameraProfile; 35import android.media.MediaRecorder; 36import android.net.Uri; 37import android.os.Build; 38import android.os.Bundle; 39import android.os.Handler; 40import android.os.Looper; 41import android.os.Message; 42import android.os.ParcelFileDescriptor; 43import android.os.SystemClock; 44import android.provider.MediaStore; 45import android.provider.MediaStore.MediaColumns; 46import android.provider.MediaStore.Video; 47import android.view.KeyEvent; 48import android.view.View; 49import android.widget.Toast; 50 51import com.android.camera.app.AppController; 52import com.android.camera.app.CameraAppUI; 53import com.android.camera.app.LocationManager; 54import com.android.camera.app.MediaSaver; 55import com.android.camera.app.MemoryManager; 56import com.android.camera.app.MemoryManager.MemoryListener; 57import com.android.camera.app.OrientationManager; 58import com.android.camera.debug.Log; 59import com.android.camera.exif.ExifInterface; 60import com.android.camera.hardware.HardwareSpec; 61import com.android.camera.hardware.HardwareSpecImpl; 62import com.android.camera.module.ModuleController; 63import com.android.camera.settings.Keys; 64import com.android.camera.settings.SettingsManager; 65import com.android.camera.settings.SettingsUtil; 66import com.android.camera.ui.TouchCoordinate; 67import com.android.camera.util.AndroidServices; 68import com.android.camera.util.ApiHelper; 69import com.android.camera.util.CameraUtil; 70import com.android.camera.stats.UsageStatistics; 71import com.android.camera.util.Size; 72import com.android.camera2.R; 73import com.android.ex.camera2.portability.CameraAgent; 74import com.android.ex.camera2.portability.CameraAgent.CameraPictureCallback; 75import com.android.ex.camera2.portability.CameraAgent.CameraProxy; 76import com.android.ex.camera2.portability.CameraCapabilities; 77import com.android.ex.camera2.portability.CameraDeviceInfo.Characteristics; 78import com.android.ex.camera2.portability.CameraSettings; 79import com.google.common.logging.eventprotos; 80 81import java.io.File; 82import java.io.IOException; 83import java.text.SimpleDateFormat; 84import java.util.ArrayList; 85import java.util.Date; 86import java.util.Iterator; 87import java.util.List; 88import java.util.Set; 89 90public class VideoModule extends CameraModule 91 implements FocusOverlayManager.Listener, MediaRecorder.OnErrorListener, 92 MediaRecorder.OnInfoListener, MemoryListener, 93 OrientationManager.OnOrientationChangeListener, VideoController { 94 95 private static final Log.Tag TAG = new Log.Tag("VideoModule"); 96 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; 103 104 private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms 105 106 /** 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. 110 */ 111 private static final String EXTRA_QUICK_CAPTURE = 112 "android.intent.extra.quickCapture"; 113 114 // module fields 115 private CameraActivity mActivity; 116 private boolean mPaused; 117 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; 121 122 private int mCameraId; 123 private CameraSettings mCameraSettings; 124 private CameraCapabilities mCameraCapabilities; 125 private HardwareSpec mHardwareSpec; 126 127 private boolean mIsInReviewMode; 128 private boolean mSnapshotInProgress = false; 129 130 // Preference must be read before starting preview. We check this before starting 131 // preview. 132 private boolean mPreferenceRead; 133 134 private boolean mIsVideoCaptureIntent; 135 private boolean mQuickCapture; 136 137 private MediaRecorder mMediaRecorder; 138 /** Manager used to mute sounds and vibrations during video recording. */ 139 private AudioManager mAudioManager; 140 /* 141 * The ringer mode that was set when video recording started. We use this to 142 * reset the mode once video recording has stopped. 143 */ 144 private int mOriginalRingerMode; 145 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; 155 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; 162 163 private CamcorderProfile mProfile; 164 165 // The video duration limit. 0 means no limit. 166 private int mMaxVideoDurationInMs; 167 168 boolean mPreviewing = false; // True if preview is started. 169 // The display rotation in degrees. This is only valid when mPreviewing is 170 // true. 171 private int mDisplayRotation; 172 private int mCameraDisplayOrientation; 173 private AppController mAppController; 174 175 private int mDesiredPreviewWidth; 176 private int mDesiredPreviewHeight; 177 private ContentResolver mContentResolver; 178 179 private LocationManager mLocationManager; 180 181 private int mPendingSwitchCameraId; 182 private final Handler mHandler = new MainHandler(); 183 private VideoUI mUI; 184 private CameraProxy mCameraDevice; 185 186 private float mZoomValue; // The current zoom ratio. 187 188 private final MediaSaver.OnMediaSavedListener mOnVideoSavedListener = 189 new MediaSaver.OnMediaSavedListener() { 190 @Override 191 public void onMediaSaved(Uri uri) { 192 if (uri != null) { 193 mCurrentVideoUri = uri; 194 mCurrentVideoUriFromMediaSaved = true; 195 onVideoSaved(); 196 mActivity.notifyNewMedia(uri); 197 } 198 } 199 }; 200 201 private final MediaSaver.OnMediaSavedListener mOnPhotoSavedListener = 202 new MediaSaver.OnMediaSavedListener() { 203 @Override 204 public void onMediaSaved(Uri uri) { 205 if (uri != null) { 206 mActivity.notifyNewMedia(uri); 207 } 208 } 209 }; 210 private FocusOverlayManager mFocusManager; 211 private boolean mMirror; 212 private boolean mFocusAreaSupported; 213 private boolean mMeteringAreaSupported; 214 215 private final CameraAgent.CameraAFCallback mAutoFocusCallback = 216 new CameraAgent.CameraAFCallback() { 217 @Override 218 public void onAutoFocus(boolean focused, CameraProxy camera) { 219 if (mPaused) { 220 return; 221 } 222 mFocusManager.onAutoFocus(focused, false); 223 } 224 }; 225 226 private final Object mAutoFocusMoveCallback = 227 ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK 228 ? new CameraAgent.CameraAFMoveCallback() { 229 @Override 230 public void onAutoFocusMoving(boolean moving, CameraProxy camera) { 231 mFocusManager.onAutoFocusMoving(moving); 232 } 233 } : null; 234 235 /** 236 * This Handler is used to post message back onto the main thread of the 237 * application. 238 */ 239 private class MainHandler extends Handler { 240 @Override 241 public void handleMessage(Message msg) { 242 switch (msg.what) { 243 244 case MSG_ENABLE_SHUTTER_BUTTON: 245 mAppController.setShutterEnabled(true); 246 break; 247 248 case MSG_UPDATE_RECORD_TIME: { 249 updateRecordingTime(); 250 break; 251 } 252 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) { 261 startPreview(); 262 } 263 if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) { 264 mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100); 265 } 266 break; 267 } 268 269 case MSG_SWITCH_CAMERA: { 270 switchCamera(); 271 break; 272 } 273 274 case MSG_SWITCH_CAMERA_START_ANIMATION: { 275 //TODO: 276 //((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera(); 277 278 // Enable all camera controls. 279 mSwitchingCamera = false; 280 break; 281 } 282 283 default: 284 Log.v(TAG, "Unhandled message: " + msg.what); 285 break; 286 } 287 } 288 } 289 290 private BroadcastReceiver mReceiver = null; 291 292 private class MyBroadcastReceiver extends BroadcastReceiver { 293 @Override 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(); 301 } 302 } 303 } 304 305 private int mShutterIconId; 306 307 308 /** 309 * Construct a new video module. 310 */ 311 public VideoModule(AppController app) { 312 super(app); 313 } 314 315 @Override 316 public String getPeekAccessibilityString() { 317 return mAppController.getAndroidContext() 318 .getResources().getString(R.string.video_accessibility_peek); 319 } 320 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)); 325 326 return dateFormat.format(date); 327 } 328 329 @Override 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(); 336 337 mActivity.updateStorageSpaceAndHint(null); 338 339 mUI = new VideoUI(mActivity, this, mActivity.getModuleLayoutRoot()); 340 mActivity.setPreviewStatusListener(mUI); 341 342 SettingsManager settingsManager = mActivity.getSettingsManager(); 343 mCameraId = settingsManager.getInteger(mAppController.getModuleScope(), 344 Keys.KEY_CAMERA_ID); 345 346 /* 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. 349 */ 350 requestCamera(mCameraId); 351 352 mContentResolver = mActivity.getContentResolver(); 353 354 // Surface texture is from camera screen nail and startPreview needs it. 355 // This must be done before startPreview. 356 mIsVideoCaptureIntent = isVideoCaptureIntent(); 357 358 mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); 359 mLocationManager = mActivity.getLocationManager(); 360 361 mUI.setOrientationIndicator(0, false); 362 setDisplayOrientation(); 363 364 mPendingSwitchCameraId = -1; 365 366 mShutterIconId = CameraUtil.getCameraShutterIconId( 367 mAppController.getCurrentModuleIndex(), mAppController.getAndroidContext()); 368 } 369 370 @Override 371 public boolean isUsingBottomBar() { 372 return true; 373 } 374 375 private void initializeControlByIntent() { 376 if (isVideoCaptureIntent()) { 377 if (!mDontResetIntentUiOnResume) { 378 mActivity.getCameraAppUI().transitionToIntentCaptureLayout(); 379 } 380 // reset the flag 381 mDontResetIntentUiOnResume = false; 382 } 383 } 384 385 @Override 386 public void onSingleTapUp(View view, int x, int y) { 387 if (mPaused || mCameraDevice == null) { 388 return; 389 } 390 if (mMediaRecorderRecording) { 391 if (!mSnapshotInProgress) { 392 takeASnapshot(); 393 } 394 return; 395 } 396 // Check if metering area or focus area is supported. 397 if (!mFocusAreaSupported && !mMeteringAreaSupported) { 398 return; 399 } 400 // Tap to focus. 401 mFocusManager.onSingleTapUp(x, y); 402 } 403 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"); 408 return; 409 } 410 if (!mIsVideoCaptureIntent) { 411 if (!mMediaRecorderRecording || mPaused || mSnapshotInProgress 412 || !mAppController.isShutterEnabled() || mCameraDevice == null) { 413 return; 414 } 415 416 Location loc = mLocationManager.getCurrentLocation(); 417 CameraUtil.setGpsParameters(mCameraSettings, loc); 418 mCameraDevice.applySettings(mCameraSettings); 419 420 Log.i(TAG, "Video snapshot start"); 421 mCameraDevice.takePicture(mHandler, 422 null, null, null, new JpegPictureCallback(loc)); 423 showVideoSnapshotUI(true); 424 mSnapshotInProgress = true; 425 } 426 } 427 428 private void updateAutoFocusMoveCallback() { 429 if (mPaused || mCameraDevice == null) { 430 return; 431 } 432 433 if (mCameraSettings.getCurrentFocusMode() == CameraCapabilities.FocusMode.CONTINUOUS_PICTURE) { 434 mCameraDevice.setAutoFocusMoveCallback(mHandler, 435 (CameraAgent.CameraAFMoveCallback) mAutoFocusMoveCallback); 436 } else { 437 mCameraDevice.setAutoFocusMoveCallback(null, null); 438 } 439 } 440 441 /** 442 * @return Whether the currently active camera is front-facing. 443 */ 444 private boolean isCameraFrontFacing() { 445 return mAppController.getCameraProvider().getCharacteristics(mCameraId) 446 .isFacingFront(); 447 } 448 449 /** 450 * @return Whether the currently active camera is back-facing. 451 */ 452 private boolean isCameraBackFacing() { 453 return mAppController.getCameraProvider().getCharacteristics(mCameraId) 454 .isFacingBack(); 455 } 456 457 /** 458 * The focus manager gets initialized after camera is available. 459 */ 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(); 466 } else { 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); 475 if (mode != null) { 476 defaultFocusModes.add(mode); 477 } 478 } 479 mFocusManager = new FocusOverlayManager(mAppController, 480 defaultFocusModes, mCameraCapabilities, this, mMirror, 481 mActivity.getMainLooper(), mUI.getFocusRing()); 482 } 483 mAppController.addPreviewAreaSizeChangedListener(mFocusManager); 484 } 485 486 @Override 487 public void onOrientationChanged(OrientationManager orientationManager, 488 OrientationManager.DeviceOrientation deviceOrientation) { 489 mUI.onOrientationChanged(orientationManager, deviceOrientation); 490 } 491 492 private final ButtonManager.ButtonCallback mFlashCallback = 493 new ButtonManager.ButtonCallback() { 494 @Override 495 public void onStateChanged(int state) { 496 if (mPaused) { 497 return; 498 } 499 // Update flash parameters. 500 enableTorchMode(true); 501 } 502 }; 503 504 private final ButtonManager.ButtonCallback mCameraCallback = 505 new ButtonManager.ButtonCallback() { 506 @Override 507 public void onStateChanged(int state) { 508 if (mPaused || mAppController.getCameraProvider().waitingForCamera()) { 509 return; 510 } 511 ButtonManager buttonManager = mActivity.getButtonManager(); 512 buttonManager.disableCameraButtonAndBlock(); 513 mPendingSwitchCameraId = state; 514 Log.d(TAG, "Start to copy texture."); 515 516 // Disable all camera controls. 517 mSwitchingCamera = true; 518 switchCamera(); 519 } 520 }; 521 522 private final View.OnClickListener mCancelCallback = new View.OnClickListener() { 523 @Override 524 public void onClick(View v) { 525 onReviewCancelClicked(v); 526 } 527 }; 528 529 private final View.OnClickListener mDoneCallback = new View.OnClickListener() { 530 @Override 531 public void onClick(View v) { 532 onReviewDoneClicked(v); 533 } 534 }; 535 private final View.OnClickListener mReviewCallback = new View.OnClickListener() { 536 @Override 537 public void onClick(View v) { 538 onReviewPlayClicked(v); 539 } 540 }; 541 542 @Override 543 public void hardResetSettings(SettingsManager settingsManager) { 544 // VideoModule does not need to hard reset any settings. 545 } 546 547 @Override 548 public HardwareSpec getHardwareSpec() { 549 if (mHardwareSpec == null) { 550 mHardwareSpec = (mCameraSettings != null ? 551 new HardwareSpecImpl(getCameraProvider(), mCameraCapabilities, 552 mAppController.getCameraFeatureConfig(), isCameraFrontFacing()) : null); 553 } 554 return mHardwareSpec; 555 } 556 557 @Override 558 public CameraAppUI.BottomBarUISpec getBottomBarSpec() { 559 CameraAppUI.BottomBarUISpec bottomBarSpec = new CameraAppUI.BottomBarUISpec(); 560 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; 569 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; 577 } 578 579 return bottomBarSpec; 580 } 581 582 @Override 583 public void onCameraAvailable(CameraProxy cameraProxy) { 584 if (cameraProxy == null) { 585 Log.w(TAG, "onCameraAvailable returns a null CameraProxy object"); 586 return; 587 } 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); 604 605 startPreview(); 606 initializeVideoSnapshot(); 607 mUI.initializeZoom(mCameraSettings, mCameraCapabilities); 608 initializeControlByIntent(); 609 610 mHardwareSpec = new HardwareSpecImpl(getCameraProvider(), mCameraCapabilities, 611 mAppController.getCameraFeatureConfig(), isCameraFrontFacing()); 612 613 ButtonManager buttonManager = mActivity.getButtonManager(); 614 buttonManager.enableCameraButton(); 615 } 616 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)); 621 try { 622 mActivity.launchActivityByIntent(intent); 623 } catch (ActivityNotFoundException ex) { 624 Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); 625 } 626 } 627 628 @Override 629 public void onReviewPlayClicked(View v) { 630 startPlayVideoActivity(); 631 } 632 633 @Override 634 public void onReviewDoneClicked(View v) { 635 mIsInReviewMode = false; 636 doReturnToCaller(true); 637 } 638 639 @Override 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); 647 } 648 mIsInReviewMode = false; 649 doReturnToCaller(false); 650 } 651 652 @Override 653 public boolean isInReviewMode() { 654 return mIsInReviewMode; 655 } 656 657 private void onStopVideoRecording() { 658 mAppController.getCameraAppUI().setSwipeEnabled(true); 659 boolean recordFail = stopVideoRecording(); 660 if (mIsVideoCaptureIntent) { 661 if (mQuickCapture) { 662 doReturnToCaller(!recordFail); 663 } else if (!recordFail) { 664 showCaptureResult(); 665 } 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); 675 } 676 } 677 } 678 679 public void onVideoSaved() { 680 if (mIsVideoCaptureIntent) { 681 showCaptureResult(); 682 } 683 } 684 685 public void onProtectiveCurtainClick(View v) { 686 // Consume clicks 687 } 688 689 @Override 690 public void onShutterButtonClick() { 691 if (mSwitchingCamera) { 692 return; 693 } 694 boolean stop = mMediaRecorderRecording; 695 696 if (stop) { 697 // CameraAppUI mishandles mode option enable/disable 698 // for video, override that 699 mAppController.getCameraAppUI().enableModeOptions(); 700 onStopVideoRecording(); 701 } else { 702 // CameraAppUI mishandles mode option enable/disable 703 // for video, override that 704 mAppController.getCameraAppUI().disableModeOptions(); 705 startVideoRecording(); 706 } 707 mAppController.setShutterEnabled(false); 708 if (mCameraSettings != null) { 709 mFocusManager.onShutterUp(mCameraSettings.getCurrentFocusMode()); 710 } 711 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); 717 } 718 } 719 720 @Override 721 public void onShutterCoordinate(TouchCoordinate coord) { 722 // Do nothing. 723 } 724 725 @Override 726 public void onShutterButtonFocus(boolean pressed) { 727 // TODO: Remove this when old camera controls are removed from the UI. 728 } 729 730 private void readVideoPreferences() { 731 // The preference stores values from ListPreference and is thus string type for all values. 732 // We need to convert it to int manually. 733 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); 740 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; 750 } 751 } 752 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)) { 756 int seconds = 757 intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0); 758 mMaxVideoDurationInMs = 1000 * seconds; 759 } else { 760 mMaxVideoDurationInMs = SettingsUtil.getMaxVideoDuration(mActivity 761 .getAndroidContext()); 762 } 763 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; 767 } 768 mProfile = CamcorderProfile.get(mCameraId, quality); 769 mPreferenceRead = true; 770 } 771 772 /** 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. 778 */ 779 private void updateDesiredPreviewSize() { 780 if (mCameraDevice == null) { 781 return; 782 } 783 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); 792 } 793 794 /** 795 * Calculates the preview size and stores it in mDesiredPreviewWidth and 796 * mDesiredPreviewHeight. 797 * 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> 805 * 806 * @return The preferred preview size or {@code null} if the camera is not 807 * opened yet. 808 */ 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); 814 } 815 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); 824 } 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) { 831 it.remove(); 832 } 833 } 834 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); 844 } 845 } 846 847 Size optimalSize = CameraUtil.getOptimalPreviewSize(sizes, 848 (double) profile.videoFrameWidth / profile.videoFrameHeight); 849 return new Point(optimalSize.width(), optimalSize.height()); 850 } 851 852 private void resizeForPreviewAspectRatio() { 853 mUI.setAspectRatio((float) mProfile.videoFrameWidth / mProfile.videoFrameHeight); 854 } 855 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); 864 } 865 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); 874 } 875 if (mFocusManager != null) { 876 mFocusManager.setDisplayOrientation(mCameraDisplayOrientation); 877 } 878 } 879 880 @Override 881 public void updateCameraOrientation() { 882 if (mMediaRecorderRecording) { 883 return; 884 } 885 if (mDisplayRotation != CameraUtil.getDisplayRotation()) { 886 setDisplayOrientation(); 887 } 888 } 889 890 @Override 891 public void updatePreviewAspectRatio(float aspectRatio) { 892 mAppController.updatePreviewAspectRatio(aspectRatio); 893 } 894 895 /** 896 * Returns current Zoom value, with 1.0 as the value for no zoom. 897 */ 898 private float currentZoomValue() { 899 return mCameraSettings.getCurrentZoomRatio(); 900 } 901 902 @Override 903 public void onZoomChanged(float ratio) { 904 // Not useful to change zoom value when the activity is paused. 905 if (mPaused) { 906 return; 907 } 908 mZoomValue = ratio; 909 if (mCameraSettings == null || mCameraDevice == null) { 910 return; 911 } 912 // Set zoom parameters asynchronously 913 mCameraSettings.setZoomRatio(mZoomValue); 914 mCameraDevice.applySettings(mCameraSettings); 915 } 916 917 private void startPreview() { 918 Log.i(TAG, "startPreview"); 919 920 SurfaceTexture surfaceTexture = mActivity.getCameraAppUI().getSurfaceTexture(); 921 if (!mPreferenceRead || surfaceTexture == null || mPaused == true || 922 mCameraDevice == null) { 923 return; 924 } 925 926 if (mPreviewing == true) { 927 stopPreview(); 928 } 929 930 setDisplayOrientation(); 931 mCameraDevice.setDisplayOrientation(mDisplayRotation); 932 setCameraParameters(); 933 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(); 941 } 942 } 943 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(); 952 } else { 953 Log.v(TAG, "on L, no one shot callback necessary"); 954 } 955 try { 956 mCameraDevice.setPreviewTexture(surfaceTexture); 957 mCameraDevice.startPreviewWithCallback(new Handler(Looper.getMainLooper()), 958 new CameraAgent.CameraStartPreviewCallback() { 959 @Override 960 public void onPreviewStarted() { 961 VideoModule.this.onPreviewStarted(); 962 } 963 }); 964 mPreviewing = true; 965 } catch (Throwable ex) { 966 closeCamera(); 967 throw new RuntimeException("startPreview failed", ex); 968 } 969 } 970 971 private void onPreviewStarted() { 972 mAppController.setShutterEnabled(true); 973 mAppController.onPreviewStarted(); 974 if (mFocusManager != null) { 975 mFocusManager.onPreviewStarted(); 976 } 977 } 978 979 @Override 980 public void onPreviewInitialDataReceived() { 981 } 982 983 @Override 984 public void stopPreview() { 985 if (!mPreviewing) { 986 Log.v(TAG, "Skip stopPreview since it's not mPreviewing"); 987 return; 988 } 989 if (mCameraDevice == null) { 990 Log.v(TAG, "Skip stopPreview since mCameraDevice is null"); 991 return; 992 } 993 994 Log.v(TAG, "stopPreview"); 995 mCameraDevice.stopPreview(); 996 if (mFocusManager != null) { 997 mFocusManager.onPreviewStopped(); 998 } 999 mPreviewing = false; 1000 } 1001 1002 private void closeCamera() { 1003 Log.i(TAG, "closeCamera"); 1004 if (mCameraDevice == null) { 1005 Log.d(TAG, "already stopped."); 1006 return; 1007 } 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(); 1015 } 1016 } 1017 1018 @Override 1019 public boolean onBackPressed() { 1020 if (mPaused) { 1021 return true; 1022 } 1023 if (mMediaRecorderRecording) { 1024 onStopVideoRecording(); 1025 return true; 1026 } else { 1027 return false; 1028 } 1029 } 1030 1031 @Override 1032 public boolean onKeyDown(int keyCode, KeyEvent event) { 1033 // Do not handle any key if the activity is paused. 1034 if (mPaused) { 1035 return true; 1036 } 1037 1038 switch (keyCode) { 1039 case KeyEvent.KEYCODE_CAMERA: 1040 if (event.getRepeatCount() == 0) { 1041 onShutterButtonClick(); 1042 return true; 1043 } 1044 case KeyEvent.KEYCODE_DPAD_CENTER: 1045 if (event.getRepeatCount() == 0) { 1046 onShutterButtonClick(); 1047 return true; 1048 } 1049 case KeyEvent.KEYCODE_MENU: 1050 // Consume menu button presses during capture. 1051 return mMediaRecorderRecording; 1052 } 1053 return false; 1054 } 1055 1056 @Override 1057 public boolean onKeyUp(int keyCode, KeyEvent event) { 1058 switch (keyCode) { 1059 case KeyEvent.KEYCODE_CAMERA: 1060 onShutterButtonClick(); 1061 return true; 1062 case KeyEvent.KEYCODE_MENU: 1063 // Consume menu button presses during capture. 1064 return mMediaRecorderRecording; 1065 } 1066 return false; 1067 } 1068 1069 @Override 1070 public boolean isVideoCaptureIntent() { 1071 String action = mActivity.getIntent().getAction(); 1072 return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); 1073 } 1074 1075 private void doReturnToCaller(boolean valid) { 1076 Intent resultIntent = new Intent(); 1077 int resultCode; 1078 if (valid) { 1079 resultCode = Activity.RESULT_OK; 1080 resultIntent.setData(mCurrentVideoUri); 1081 resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 1082 } else { 1083 resultCode = Activity.RESULT_CANCELED; 1084 } 1085 mActivity.setResultEx(resultCode, resultIntent); 1086 mActivity.finish(); 1087 } 1088 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; 1095 } 1096 } 1097 } 1098 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"); 1105 return; 1106 } 1107 Intent intent = mActivity.getIntent(); 1108 Bundle myExtras = intent.getExtras(); 1109 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) { 1116 try { 1117 mVideoFileDescriptor = 1118 mContentResolver.openFileDescriptor(saveUri, "rw"); 1119 mCurrentVideoUri = saveUri; 1120 } catch (java.io.FileNotFoundException ex) { 1121 // invalid uri 1122 Log.e(TAG, ex.toString()); 1123 } 1124 } 1125 requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT); 1126 } 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"); 1139 return; 1140 } 1141 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); 1148 1149 setRecordLocation(); 1150 1151 // Set output file. 1152 // Try Uri in the intent first. If it doesn't exist, use our own 1153 // instead. 1154 if (mVideoFileDescriptor != null) { 1155 mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor()); 1156 } else { 1157 generateVideoFilename(mProfile.fileFormat); 1158 mMediaRecorder.setOutputFile(mVideoFilename); 1159 } 1160 1161 // Set maximum file size. 1162 long maxFileSize = mActivity.getStorageSpaceBytes() - Storage.LOW_STORAGE_THRESHOLD_BYTES; 1163 if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) { 1164 maxFileSize = requestedSizeLimit; 1165 } 1166 1167 try { 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. 1174 } 1175 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); 1183 1184 try { 1185 mMediaRecorder.prepare(); 1186 } catch (IOException e) { 1187 Log.e(TAG, "prepare failed for " + mVideoFilename, e); 1188 releaseMediaRecorder(); 1189 throw new RuntimeException(e); 1190 } 1191 1192 mMediaRecorder.setOnErrorListener(this); 1193 mMediaRecorder.setOnInfoListener(this); 1194 } 1195 1196 private static void setCaptureRate(MediaRecorder recorder, double fps) { 1197 recorder.setCaptureRate(fps); 1198 } 1199 1200 private void setRecordLocation() { 1201 Location loc = mLocationManager.getCurrentLocation(); 1202 if (loc != null) { 1203 mMediaRecorder.setLocation((float) loc.getLatitude(), 1204 (float) loc.getLongitude()); 1205 } 1206 } 1207 1208 private void releaseMediaRecorder() { 1209 Log.i(TAG, "Releasing media recorder."); 1210 if (mMediaRecorder != null) { 1211 cleanupEmptyFile(); 1212 mMediaRecorder.reset(); 1213 mMediaRecorder.release(); 1214 mMediaRecorder = null; 1215 } 1216 mVideoFilename = null; 1217 } 1218 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(); 1240 if (loc != null) { 1241 mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude()); 1242 mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude()); 1243 } 1244 mVideoFilename = tmpPath; 1245 Log.v(TAG, "New video filename: " + mVideoFilename); 1246 } 1247 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); 1259 } 1260 1261 private void saveVideo() { 1262 if (mVideoFileDescriptor == null) { 1263 long duration = SystemClock.uptimeMillis() - mRecordingStartTime; 1264 if (duration > 0) { 1265 // 1266 } else { 1267 Log.w(TAG, "Video duration <= 0 : " + duration); 1268 } 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); 1274 } 1275 mCurrentVideoValues = null; 1276 } 1277 1278 private void deleteVideoFile(String fileName) { 1279 Log.v(TAG, "Deleting video " + fileName); 1280 File f = new File(fileName); 1281 if (!f.delete()) { 1282 Log.v(TAG, "Could not delete " + fileName); 1283 } 1284 } 1285 1286 // from MediaRecorder.OnErrorListener 1287 @Override 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); 1294 } 1295 } 1296 1297 // from MediaRecorder.OnInfoListener 1298 @Override 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(); 1303 } 1304 } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { 1305 if (mMediaRecorderRecording) { 1306 onStopVideoRecording(); 1307 } 1308 1309 // Show the toast. 1310 Toast.makeText(mActivity, R.string.video_reach_size_limit, 1311 Toast.LENGTH_LONG).show(); 1312 } 1313 } 1314 1315 /* 1316 * Make sure we're not recording music playing in the background, ask the 1317 * MediaPlaybackService to pause playback. 1318 */ 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 1324 // finished. 1325 mOriginalRingerMode = mAudioManager.getRingerMode(); 1326 // TODO: Use new DND APIs to properly silence device 1327 } 1328 1329 private void restoreRingerMode() { 1330 // First check if ringer mode was changed during the recording. If not, 1331 // re-set the mode that was set before video recording started. 1332 if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) { 1333 // TODO: Use new DND APIs to properly restore device notification/alarm settings 1334 } 1335 } 1336 1337 // For testing. 1338 public boolean isRecording() { 1339 return mMediaRecorderRecording; 1340 } 1341 1342 private void startVideoRecording() { 1343 Log.i(TAG, "startVideoRecording: " + Thread.currentThread()); 1344 mUI.cancelAnimations(); 1345 mUI.setSwipingEnabled(false); 1346 mUI.hidePassiveFocusIndicator(); 1347 mAppController.getCameraAppUI().hideCaptureIndicator(); 1348 mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(true); 1349 1350 mActivity.updateStorageSpaceAndHint(new CameraActivity.OnStorageUpdateDoneListener() { 1351 @Override 1352 public void onStorageUpdateDone(long bytes) { 1353 if (bytes <= Storage.LOW_STORAGE_THRESHOLD_BYTES) { 1354 Log.w(TAG, "Storage issue, ignore the start request"); 1355 } else { 1356 if (mCameraDevice == null) { 1357 Log.v(TAG, "in storage callback after camera closed"); 1358 return; 1359 } 1360 if (mPaused == true) { 1361 Log.v(TAG, "in storage callback after module paused"); 1362 return; 1363 } 1364 1365 // Monkey is so fast so it could trigger startVideoRecording twice. To prevent 1366 // app crash (b/17313985), do nothing here for the second storage-checking 1367 // callback because recording is already started. 1368 if (mMediaRecorderRecording) { 1369 Log.v(TAG, "in storage callback after recording started"); 1370 return; 1371 } 1372 1373 mCurrentVideoUri = null; 1374 1375 initializeRecorder(); 1376 if (mMediaRecorder == null) { 1377 Log.e(TAG, "Fail to initialize media recorder"); 1378 return; 1379 } 1380 1381 try { 1382 mMediaRecorder.start(); // Recording is now started 1383 } catch (RuntimeException e) { 1384 Log.e(TAG, "Could not start media recorder. ", e); 1385 mAppController.getFatalErrorHandler().onGenericCameraAccessFailure(); 1386 releaseMediaRecorder(); 1387 // If start fails, frameworks will not lock the camera for us. 1388 mCameraDevice.lock(); 1389 return; 1390 } 1391 // Make sure we stop playing sounds and disable the 1392 // vibrations during video recording. Post delayed to avoid 1393 // silencing the recording start sound. 1394 mHandler.postDelayed(new Runnable() { 1395 @Override 1396 public void run() { 1397 silenceSoundsAndVibrations(); 1398 } 1399 }, 250); 1400 1401 mAppController.getCameraAppUI().setSwipeEnabled(false); 1402 1403 // The parameters might have been altered by MediaRecorder already. 1404 // We need to force mCameraDevice to refresh before getting it. 1405 mCameraDevice.refreshSettings(); 1406 // The parameters may have been changed by MediaRecorder upon starting 1407 // recording. We need to alter the parameters if we support camcorder 1408 // zoom. To reduce latency when setting the parameters during zoom, we 1409 // update the settings here once. 1410 mCameraSettings = mCameraDevice.getSettings(); 1411 1412 mMediaRecorderRecording = true; 1413 mActivity.lockOrientation(); 1414 mRecordingStartTime = SystemClock.uptimeMillis(); 1415 1416 // A special case of mode options closing: during capture it should 1417 // not be possible to change mode state. 1418 mAppController.getCameraAppUI().hideModeOptions(); 1419 mAppController.getCameraAppUI().animateBottomBarToVideoStop(R.drawable.ic_stop); 1420 mUI.showRecordingUI(true); 1421 1422 setFocusParameters(); 1423 1424 updateRecordingTime(); 1425 mActivity.enableKeepScreenOn(true); 1426 } 1427 } 1428 }); 1429 } 1430 1431 private Bitmap getVideoThumbnail() { 1432 Bitmap bitmap = null; 1433 if (mVideoFileDescriptor != null) { 1434 bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(), 1435 mDesiredPreviewWidth); 1436 } else if (mCurrentVideoUri != null) { 1437 try { 1438 mVideoFileDescriptor = mContentResolver.openFileDescriptor(mCurrentVideoUri, "r"); 1439 bitmap = Thumbnail.createVideoThumbnailBitmap( 1440 mVideoFileDescriptor.getFileDescriptor(), mDesiredPreviewWidth); 1441 } catch (java.io.FileNotFoundException ex) { 1442 // invalid uri 1443 Log.e(TAG, ex.toString()); 1444 } 1445 } 1446 1447 if (bitmap != null) { 1448 // MetadataRetriever already rotates the thumbnail. We should rotate 1449 // it to match the UI orientation (and mirror if it is front-facing camera). 1450 bitmap = CameraUtil.rotateAndMirror(bitmap, 0, isCameraFrontFacing()); 1451 } 1452 return bitmap; 1453 } 1454 1455 private void showCaptureResult() { 1456 mIsInReviewMode = true; 1457 Bitmap bitmap = getVideoThumbnail(); 1458 if (bitmap != null) { 1459 mUI.showReviewImage(bitmap); 1460 } 1461 mUI.showReviewControls(); 1462 } 1463 1464 private boolean stopVideoRecording() { 1465 // Do nothing if camera device is still capturing photo. Monkey test can trigger app crashes 1466 // (b/17313985) without this check. Crash could also be reproduced by continuously tapping 1467 // on shutter button and preview with two fingers. 1468 if (mSnapshotInProgress) { 1469 Log.v(TAG, "Skip stopVideoRecording since snapshot in progress"); 1470 return true; 1471 } 1472 Log.v(TAG, "stopVideoRecording"); 1473 1474 // Re-enable sound as early as possible to avoid interfering with stop 1475 // recording sound. 1476 restoreRingerMode(); 1477 1478 mUI.setSwipingEnabled(true); 1479 mUI.showPassiveFocusIndicator(); 1480 mAppController.getCameraAppUI().setShouldSuppressCaptureIndicator(false); 1481 1482 boolean fail = false; 1483 if (mMediaRecorderRecording) { 1484 boolean shouldAddToMediaStoreNow = false; 1485 1486 try { 1487 mMediaRecorder.setOnErrorListener(null); 1488 mMediaRecorder.setOnInfoListener(null); 1489 mMediaRecorder.stop(); 1490 shouldAddToMediaStoreNow = true; 1491 mCurrentVideoFilename = mVideoFilename; 1492 Log.v(TAG, "stopVideoRecording: current video filename: " + mCurrentVideoFilename); 1493 } catch (RuntimeException e) { 1494 Log.e(TAG, "stop fail", e); 1495 if (mVideoFilename != null) { 1496 deleteVideoFile(mVideoFilename); 1497 } 1498 fail = true; 1499 } 1500 mMediaRecorderRecording = false; 1501 mActivity.unlockOrientation(); 1502 1503 // If the activity is paused, this means activity is interrupted 1504 // during recording. Release the camera as soon as possible because 1505 // face unlock or other applications may need to use the camera. 1506 if (mPaused) { 1507 // b/16300704: Monkey is fast so it could pause the module while recording. 1508 // stopPreview should definitely be called before switching off. 1509 stopPreview(); 1510 closeCamera(); 1511 } 1512 1513 mUI.showRecordingUI(false); 1514 // The orientation was fixed during video recording. Now make it 1515 // reflect the device orientation as video recording is stopped. 1516 mUI.setOrientationIndicator(0, true); 1517 mActivity.enableKeepScreenOn(false); 1518 if (shouldAddToMediaStoreNow && !fail) { 1519 if (mVideoFileDescriptor == null) { 1520 saveVideo(); 1521 } else if (mIsVideoCaptureIntent) { 1522 // if no file save is needed, we can show the post capture UI now 1523 showCaptureResult(); 1524 } 1525 } 1526 } 1527 // release media recorder 1528 releaseMediaRecorder(); 1529 1530 mAppController.getCameraAppUI().showModeOptions(); 1531 mAppController.getCameraAppUI().animateBottomBarToFullSize(mShutterIconId); 1532 if (!mPaused && mCameraDevice != null) { 1533 setFocusParameters(); 1534 mCameraDevice.lock(); 1535 if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { 1536 stopPreview(); 1537 // Switch back to use SurfaceTexture for preview. 1538 startPreview(); 1539 } 1540 // Update the parameters here because the parameters might have been altered 1541 // by MediaRecorder. 1542 mCameraSettings = mCameraDevice.getSettings(); 1543 } 1544 1545 // Check this in advance of each shot so we don't add to shutter 1546 // latency. It's true that someone else could write to the SD card 1547 // in the mean time and fill it, but that could have happened 1548 // between the shutter press and saving the file too. 1549 mActivity.updateStorageSpaceAndHint(null); 1550 1551 return fail; 1552 } 1553 1554 private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) { 1555 long seconds = milliSeconds / 1000; // round down to compute seconds 1556 long minutes = seconds / 60; 1557 long hours = minutes / 60; 1558 long remainderMinutes = minutes - (hours * 60); 1559 long remainderSeconds = seconds - (minutes * 60); 1560 1561 StringBuilder timeStringBuilder = new StringBuilder(); 1562 1563 // Hours 1564 if (hours > 0) { 1565 if (hours < 10) { 1566 timeStringBuilder.append('0'); 1567 } 1568 timeStringBuilder.append(hours); 1569 1570 timeStringBuilder.append(':'); 1571 } 1572 1573 // Minutes 1574 if (remainderMinutes < 10) { 1575 timeStringBuilder.append('0'); 1576 } 1577 timeStringBuilder.append(remainderMinutes); 1578 timeStringBuilder.append(':'); 1579 1580 // Seconds 1581 if (remainderSeconds < 10) { 1582 timeStringBuilder.append('0'); 1583 } 1584 timeStringBuilder.append(remainderSeconds); 1585 1586 // Centi seconds 1587 if (displayCentiSeconds) { 1588 timeStringBuilder.append('.'); 1589 long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10; 1590 if (remainderCentiSeconds < 10) { 1591 timeStringBuilder.append('0'); 1592 } 1593 timeStringBuilder.append(remainderCentiSeconds); 1594 } 1595 1596 return timeStringBuilder.toString(); 1597 } 1598 1599 private void updateRecordingTime() { 1600 if (!mMediaRecorderRecording) { 1601 return; 1602 } 1603 long now = SystemClock.uptimeMillis(); 1604 long delta = now - mRecordingStartTime; 1605 1606 // Starting a minute before reaching the max duration 1607 // limit, we'll countdown the remaining time instead. 1608 boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0 1609 && delta >= mMaxVideoDurationInMs - 60000); 1610 1611 long deltaAdjusted = delta; 1612 if (countdownRemainingTime) { 1613 deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999; 1614 } 1615 String text; 1616 1617 long targetNextUpdateDelay; 1618 1619 text = millisecondToTimeString(deltaAdjusted, false); 1620 targetNextUpdateDelay = 1000; 1621 1622 mUI.setRecordingTime(text); 1623 1624 if (mRecordingTimeCountsDown != countdownRemainingTime) { 1625 // Avoid setting the color on every update, do it only 1626 // when it needs changing. 1627 mRecordingTimeCountsDown = countdownRemainingTime; 1628 1629 int color = mActivity.getResources().getColor(R.color.recording_time_remaining_text); 1630 1631 mUI.setRecordingTimeTextColor(color); 1632 } 1633 1634 long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay); 1635 mHandler.sendEmptyMessageDelayed(MSG_UPDATE_RECORD_TIME, actualNextUpdateDelay); 1636 } 1637 1638 private static boolean isSupported(String value, List<String> supported) { 1639 return supported == null ? false : supported.indexOf(value) >= 0; 1640 } 1641 1642 @SuppressWarnings("deprecation") 1643 private void setCameraParameters() { 1644 SettingsManager settingsManager = mActivity.getSettingsManager(); 1645 1646 // Update Desired Preview size in case video camera resolution has changed. 1647 updateDesiredPreviewSize(); 1648 1649 Size previewSize = new Size(mDesiredPreviewWidth, mDesiredPreviewHeight); 1650 mCameraSettings.setPreviewSize(previewSize.toPortabilitySize()); 1651 // This is required for Samsung SGH-I337 and probably other Samsung S4 versions 1652 if (Build.BRAND.toLowerCase().contains("samsung")) { 1653 mCameraSettings.setSetting("video-size", 1654 mProfile.videoFrameWidth + "x" + mProfile.videoFrameHeight); 1655 } 1656 int[] fpsRange = 1657 CameraUtil.getMaxPreviewFpsRange(mCameraCapabilities.getSupportedPreviewFpsRange()); 1658 if (fpsRange.length > 0) { 1659 mCameraSettings.setPreviewFpsRange(fpsRange[0], fpsRange[1]); 1660 } else { 1661 mCameraSettings.setPreviewFrameRate(mProfile.videoFrameRate); 1662 } 1663 1664 enableTorchMode(Keys.isCameraBackFacing(settingsManager, mAppController.getModuleScope())); 1665 1666 // Set zoom. 1667 if (mCameraCapabilities.supports(CameraCapabilities.Feature.ZOOM)) { 1668 mCameraSettings.setZoomRatio(mZoomValue); 1669 } 1670 updateFocusParameters(); 1671 1672 mCameraSettings.setRecordingHintEnabled(true); 1673 1674 if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_STABILIZATION)) { 1675 mCameraSettings.setVideoStabilization(true); 1676 } 1677 1678 // Set picture size. 1679 // The logic here is different from the logic in still-mode camera. 1680 // There we determine the preview size based on the picture size, but 1681 // here we determine the picture size based on the preview size. 1682 List<Size> supported = Size.convert(mCameraCapabilities.getSupportedPhotoSizes()); 1683 Size optimalSize = CameraUtil.getOptimalVideoSnapshotPictureSize(supported, 1684 mDesiredPreviewWidth, mDesiredPreviewHeight); 1685 Size original = new Size(mCameraSettings.getCurrentPhotoSize()); 1686 if (!original.equals(optimalSize)) { 1687 mCameraSettings.setPhotoSize(optimalSize.toPortabilitySize()); 1688 } 1689 Log.d(TAG, "Video snapshot size is " + optimalSize); 1690 1691 // Set JPEG quality. 1692 int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, 1693 CameraProfile.QUALITY_HIGH); 1694 mCameraSettings.setPhotoJpegCompressionQuality(jpegQuality); 1695 1696 if (mCameraDevice != null) { 1697 mCameraDevice.applySettings(mCameraSettings); 1698 // Nexus 5 through KitKat 4.4.2 requires a second call to 1699 // .setParameters() for frame rate settings to take effect. 1700 mCameraDevice.applySettings(mCameraSettings); 1701 } 1702 1703 // Update UI based on the new parameters. 1704 mUI.updateOnScreenIndicators(mCameraSettings); 1705 } 1706 1707 private void updateFocusParameters() { 1708 // Set continuous autofocus. During recording, we use "continuous-video" 1709 // auto focus mode to ensure smooth focusing. Whereas during preview (i.e. 1710 // before recording starts) we use "continuous-picture" auto focus mode 1711 // for faster but slightly jittery focusing. 1712 Set<CameraCapabilities.FocusMode> supportedFocus = mCameraCapabilities 1713 .getSupportedFocusModes(); 1714 if (mMediaRecorderRecording) { 1715 if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO)) { 1716 mCameraSettings.setFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO); 1717 mFocusManager.overrideFocusMode(CameraCapabilities.FocusMode.CONTINUOUS_VIDEO); 1718 } else { 1719 mFocusManager.overrideFocusMode(null); 1720 } 1721 } else { 1722 // FIXME(b/16984793): This is broken. For some reasons, CONTINUOUS_PICTURE is not on 1723 // when preview starts. 1724 mFocusManager.overrideFocusMode(null); 1725 if (mCameraCapabilities.supports(CameraCapabilities.FocusMode.CONTINUOUS_PICTURE)) { 1726 mCameraSettings.setFocusMode( 1727 mFocusManager.getFocusMode(mCameraSettings.getCurrentFocusMode())); 1728 if (mFocusAreaSupported) { 1729 mCameraSettings.setFocusAreas(mFocusManager.getFocusAreas()); 1730 } 1731 } 1732 } 1733 updateAutoFocusMoveCallback(); 1734 } 1735 1736 @Override 1737 public void resume() { 1738 if (isVideoCaptureIntent()) { 1739 mDontResetIntentUiOnResume = mPaused; 1740 } 1741 1742 mPaused = false; 1743 installIntentFilter(); 1744 mAppController.setShutterEnabled(false); 1745 mZoomValue = 1.0f; 1746 1747 OrientationManager orientationManager = mAppController.getOrientationManager(); 1748 orientationManager.addOnOrientationChangeListener(this); 1749 mUI.onOrientationChanged(orientationManager, orientationManager.getDeviceOrientation()); 1750 1751 showVideoSnapshotUI(false); 1752 1753 if (!mPreviewing) { 1754 requestCamera(mCameraId); 1755 } else { 1756 // preview already started 1757 mAppController.setShutterEnabled(true); 1758 } 1759 1760 if (mFocusManager != null) { 1761 // If camera is not open when resume is called, focus manager will not 1762 // be initialized yet, in which case it will start listening to 1763 // preview area size change later in the initialization. 1764 mAppController.addPreviewAreaSizeChangedListener(mFocusManager); 1765 } 1766 1767 if (mPreviewing) { 1768 mOnResumeTime = SystemClock.uptimeMillis(); 1769 mHandler.sendEmptyMessageDelayed(MSG_CHECK_DISPLAY_ROTATION, 100); 1770 } 1771 getServices().getMemoryManager().addListener(this); 1772 } 1773 1774 @Override 1775 public void pause() { 1776 mPaused = true; 1777 1778 mAppController.getOrientationManager().removeOnOrientationChangeListener(this); 1779 1780 if (mFocusManager != null) { 1781 // If camera is not open when resume is called, focus manager will not 1782 // be initialized yet, in which case it will start listening to 1783 // preview area size change later in the initialization. 1784 mAppController.removePreviewAreaSizeChangedListener(mFocusManager); 1785 mFocusManager.removeMessages(); 1786 } 1787 if (mMediaRecorderRecording) { 1788 // Camera will be released in onStopVideoRecording. 1789 onStopVideoRecording(); 1790 } else { 1791 stopPreview(); 1792 closeCamera(); 1793 releaseMediaRecorder(); 1794 } 1795 1796 closeVideoFileDescriptor(); 1797 1798 if (mReceiver != null) { 1799 mActivity.unregisterReceiver(mReceiver); 1800 mReceiver = null; 1801 } 1802 1803 mHandler.removeMessages(MSG_CHECK_DISPLAY_ROTATION); 1804 mHandler.removeMessages(MSG_SWITCH_CAMERA); 1805 mHandler.removeMessages(MSG_SWITCH_CAMERA_START_ANIMATION); 1806 mPendingSwitchCameraId = -1; 1807 mSwitchingCamera = false; 1808 mPreferenceRead = false; 1809 getServices().getMemoryManager().removeListener(this); 1810 mUI.onPause(); 1811 } 1812 1813 @Override 1814 public void destroy() { 1815 1816 } 1817 1818 @Override 1819 public void onLayoutOrientationChanged(boolean isLandscape) { 1820 setDisplayOrientation(); 1821 } 1822 1823 // TODO: integrate this into the SettingsManager listeners. 1824 public void onSharedPreferenceChanged() { 1825 1826 } 1827 1828 private void switchCamera() { 1829 if (mPaused) { 1830 return; 1831 } 1832 SettingsManager settingsManager = mActivity.getSettingsManager(); 1833 1834 Log.d(TAG, "Start to switch camera."); 1835 mCameraId = mPendingSwitchCameraId; 1836 mPendingSwitchCameraId = -1; 1837 settingsManager.set(mAppController.getModuleScope(), 1838 Keys.KEY_CAMERA_ID, mCameraId); 1839 1840 if (mFocusManager != null) { 1841 mFocusManager.removeMessages(); 1842 } 1843 closeCamera(); 1844 requestCamera(mCameraId); 1845 1846 mMirror = isCameraFrontFacing(); 1847 if (mFocusManager != null) { 1848 mFocusManager.setMirror(mMirror); 1849 } 1850 1851 // From onResume 1852 mZoomValue = 1.0f; 1853 mUI.setOrientationIndicator(0, false); 1854 1855 // Start switch camera animation. Post a message because 1856 // onFrameAvailable from the old camera may already exist. 1857 mHandler.sendEmptyMessage(MSG_SWITCH_CAMERA_START_ANIMATION); 1858 mUI.updateOnScreenIndicators(mCameraSettings); 1859 } 1860 1861 private void initializeVideoSnapshot() { 1862 if (mCameraSettings == null) { 1863 return; 1864 } 1865 } 1866 1867 void showVideoSnapshotUI(boolean enabled) { 1868 if (mCameraSettings == null) { 1869 return; 1870 } 1871 if (mCameraCapabilities.supports(CameraCapabilities.Feature.VIDEO_SNAPSHOT) && 1872 !mIsVideoCaptureIntent) { 1873 if (enabled) { 1874 mAppController.startFlashAnimation(false); 1875 } else { 1876 mUI.showPreviewBorder(enabled); 1877 } 1878 mAppController.setShutterEnabled(!enabled); 1879 } 1880 } 1881 1882 /** 1883 * Used to update the flash mode. Video mode can turn on the flash as torch 1884 * mode, which we would like to turn on and off when we switching in and 1885 * out to the preview. 1886 * 1887 * @param enable Whether torch mode can be enabled. 1888 */ 1889 private void enableTorchMode(boolean enable) { 1890 if (mCameraSettings.getCurrentFlashMode() == null) { 1891 return; 1892 } 1893 1894 SettingsManager settingsManager = mActivity.getSettingsManager(); 1895 1896 CameraCapabilities.Stringifier stringifier = mCameraCapabilities.getStringifier(); 1897 CameraCapabilities.FlashMode flashMode; 1898 if (enable) { 1899 flashMode = stringifier 1900 .flashModeFromString(settingsManager.getString(mAppController.getCameraScope(), 1901 Keys.KEY_VIDEOCAMERA_FLASH_MODE)); 1902 } else { 1903 flashMode = CameraCapabilities.FlashMode.OFF; 1904 } 1905 if (mCameraCapabilities.supports(flashMode)) { 1906 mCameraSettings.setFlashMode(flashMode); 1907 } 1908 /* TODO: Find out how to deal with the following code piece: 1909 else { 1910 flashMode = mCameraSettings.getCurrentFlashMode(); 1911 if (flashMode == null) { 1912 flashMode = mActivity.getString( 1913 R.string.pref_camera_flashmode_no_flash); 1914 mParameters.setFlashMode(flashMode); 1915 } 1916 }*/ 1917 if (mCameraDevice != null) { 1918 mCameraDevice.applySettings(mCameraSettings); 1919 } 1920 mUI.updateOnScreenIndicators(mCameraSettings); 1921 } 1922 1923 @Override 1924 public void onPreviewVisibilityChanged(int visibility) { 1925 if (mPreviewing) { 1926 enableTorchMode(visibility == ModuleController.VISIBILITY_VISIBLE); 1927 } 1928 } 1929 1930 private final class JpegPictureCallback implements CameraPictureCallback { 1931 Location mLocation; 1932 1933 public JpegPictureCallback(Location loc) { 1934 mLocation = loc; 1935 } 1936 1937 @Override 1938 public void onPictureTaken(byte [] jpegData, CameraProxy camera) { 1939 Log.i(TAG, "Video snapshot taken."); 1940 mSnapshotInProgress = false; 1941 showVideoSnapshotUI(false); 1942 storeImage(jpegData, mLocation); 1943 } 1944 } 1945 1946 private void storeImage(final byte[] data, Location loc) { 1947 long dateTaken = System.currentTimeMillis(); 1948 String title = CameraUtil.instance().createJpegName(dateTaken); 1949 ExifInterface exif = Exif.getExif(data); 1950 int orientation = Exif.getOrientation(exif); 1951 1952 String flashSetting = mActivity.getSettingsManager() 1953 .getString(mAppController.getCameraScope(), Keys.KEY_VIDEOCAMERA_FLASH_MODE); 1954 Boolean gridLinesOn = Keys.areGridLinesOn(mActivity.getSettingsManager()); 1955 UsageStatistics.instance().photoCaptureDoneEvent( 1956 eventprotos.NavigationChange.Mode.VIDEO_STILL, title + ".jpeg", exif, 1957 isCameraFrontFacing(), false, currentZoomValue(), flashSetting, gridLinesOn, 1958 null, null, null, null, null, null, null); 1959 1960 getServices().getMediaSaver().addImage(data, title, dateTaken, loc, orientation, exif, 1961 mOnPhotoSavedListener); 1962 } 1963 1964 private String convertOutputFormatToMimeType(int outputFileFormat) { 1965 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) { 1966 return "video/mp4"; 1967 } 1968 return "video/3gpp"; 1969 } 1970 1971 private String convertOutputFormatToFileExt(int outputFileFormat) { 1972 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) { 1973 return ".mp4"; 1974 } 1975 return ".3gp"; 1976 } 1977 1978 private void closeVideoFileDescriptor() { 1979 if (mVideoFileDescriptor != null) { 1980 try { 1981 mVideoFileDescriptor.close(); 1982 } catch (IOException e) { 1983 Log.e(TAG, "Fail to close fd", e); 1984 } 1985 mVideoFileDescriptor = null; 1986 } 1987 } 1988 1989 @Override 1990 public void onPreviewUIReady() { 1991 startPreview(); 1992 } 1993 1994 @Override 1995 public void onPreviewUIDestroyed() { 1996 stopPreview(); 1997 } 1998 1999 private void requestCamera(int id) { 2000 mActivity.getCameraProvider().requestCamera(id); 2001 } 2002 2003 @Override 2004 public void onMemoryStateChanged(int state) { 2005 mAppController.setShutterEnabled(state == MemoryManager.STATE_OK); 2006 } 2007 2008 @Override 2009 public void onLowMemory() { 2010 // Not much we can do in the video module. 2011 } 2012 2013 /***********************FocusOverlayManager Listener****************************/ 2014 @Override 2015 public void autoFocus() { 2016 if (mCameraDevice != null) { 2017 mCameraDevice.autoFocus(mHandler, mAutoFocusCallback); 2018 } 2019 } 2020 2021 @Override 2022 public void cancelAutoFocus() { 2023 if (mCameraDevice != null) { 2024 mCameraDevice.cancelAutoFocus(); 2025 setFocusParameters(); 2026 } 2027 } 2028 2029 @Override 2030 public boolean capture() { 2031 return false; 2032 } 2033 2034 @Override 2035 public void startFaceDetection() { 2036 2037 } 2038 2039 @Override 2040 public void stopFaceDetection() { 2041 2042 } 2043 2044 @Override 2045 public void setFocusParameters() { 2046 if (mCameraDevice != null) { 2047 updateFocusParameters(); 2048 mCameraDevice.applySettings(mCameraSettings); 2049 } 2050 } 2051} 2052