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