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