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