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