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