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