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