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