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